How to Reference a JavaScript file from a Content Page

When developers reference a JavaScript file in a Master Page and have to use it only in a couple of Content Pages, there is an extra overhead involved, since the file gets referenced for every Content page. To avoid this overhead, you can reference the JavaScript file directly from the Content Pages where the script will be used. Here’s how:

C#

protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptInclude("selective",
ResolveUrl(@"Scripts\TestScript.js"));
if (!Master.Page.ClientScript.IsStartupScriptRegistered("alert"))
{
Master.Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "insideJS();", true);
}
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Page.ClientScript.RegisterClientScriptInclude("selective", _
ResolveUrl("Scripts\TestScript.js"))
If (Not Master.Page.ClientScript.IsStartupScriptRegistered("alert")) Then
Master.Page.ClientScript.RegisterStartupScript(Me.GetType(), _
"alert", "insideJS();", True)
End If
End Sub

As you can observe, we add a reference to the .js file (TestScript.js) from the Content Page using the ‘RegisterClientScriptInclude’ and then use ClientScript.RegisterStartupScript to register the script with the Page object

I have covered plenty of similar tips and tips tricks of calling JavaScript from Master and Content Pages over here

Calling JavaScript from ASP.NET Master Page and Content Pages - Part I

Calling JavaScript from ASP.NET Master Page and Content Pages - Part II



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

JavascriptBank.com said...

very cool & good post, thank you very much for sharing.