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:


protected void Page_Load(object sender, EventArgs e)
if (!Master.Page.ClientScript.IsStartupScriptRegistered("alert"))
(this.GetType(), "alert", "insideJS();", true);


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Page.ClientScript.RegisterClientScriptInclude("selective", _
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

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment: said...

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