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


Bookmark this link on del.icio.us (saved by 0 users)

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

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 2010 All Rights Reserved DevCurry.com by Suprotim Agarwal