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
Tweet
1 comment:
very cool & good post, thank you very much for sharing.
Post a Comment