Add JavaScript inside Head at runtime

I was wondering how can I emit JavaScript within the <HEAD> element of ASP.NET page from code behind.  I knew that we can insert JavaScript using RegisterClientScriptBlock and RegisterStartUpScript but those method is being used to add JavaScript block within the <Body> tag.  Finally I found the solution to emit JavaScript within the <HEAD> section.

One nice thing is that we can access Head element of  the Page using Page’s Header property(new feature was added in ASP.NET 2.0).

For example

this.Header.Title = "Page Title";

That ‘s what I was looking for.  Now I can create HTMLGenericControl and wrap some JavaScript inside HTMLGeneriControl and add that in Header object.

Here is the sample how you can do that.
1)  Add some JavaScript inside page header

protected void Page_Load(object sender, EventArgs e)
{
System.Web.UI.HtmlControls.HtmlGenericControl si = new System.Web.UI.HtmlControls.HtmlGenericControl();
si.TagName ="script";
si.Attributes.Add("type",@"textjavascript");
si.InnerText = @"alert('I am in Head Element.')";
this.Page.Header.Controls.Add(si);
}

2)  Add .js file reference inside page header

protected void Page_Load(object sender, EventArgs e)
 {
 System.Web.UI.HtmlControls.HtmlGenericControl si = new System.Web.UI.HtmlControls.HtmlGenericControl();
 si.TagName ="script";
 si.Attributes.Add("type",@"textjavascript");
 si.Attributes.Add("src","util.js");
 this.Page.Header.Controls.Add(si);
 }

Hope this helps,
Shailesh

Posted in Microsoft Technology Tagged with:
One comment on “Add JavaScript inside Head at runtime
  1. saurabh mahajan says:

    thanks .its a good article…
    but it is more better if we use “text/javascript” in place of
    “textjavascript” because mozilla does’t support it.
    Thanks for the article it really helps me…

Ads