jQuery and ASP.NET

February 4, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "How to Reference a JavaScript file from a Content Page"
  1. JavascriptBank.com said...
    February 9, 2010 7:57 PM

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

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions