Register Script into Page Header from ASP.NET Content Page

In a previous article, I had explained how to Call a JavaScript function from ASP.NET Content Page.

We used the ‘RegisterClientScriptInclude’ to register script from a Content Page. However this approach adds the JavaScript reference inside the <body> tag of the page and not the <head>. A reader Simone mailed me asking if it was possible to use the same method to register the script into <head> portion of the page.

The answer is using the ‘RegisterClientScriptInclude’, I think it is not possible natively to add script to the <head> element. However there is an alternate method using the System.Web.UI.HtmlControls.HtmlGenericControl class as shown below:

protected void Page_Load(object sender, EventArgs e)
{
HtmlGenericControl ctrl = new HtmlGenericControl("script");
ctrl.Attributes.Add("type", "text/javascript");
ctrl.Attributes.Add("src", @"Scripts\Alert.js");
this.Page.Header.Controls.Add(ctrl);
}

Run the application, right click the page and View Source.

As you can see, the script is now registered in the <head> instead of the <body>.






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.

2 comments:

Abhishek Sur said...

But we can also use ContentPlaceHolder in Head of masterpage.

Any special advantage we could get from dynamically producing script block ? For me Html design is easier to handle

:)

Suprotim Agarwal said...

Abhishek: The advantage is in cases when your client script depends on information that is not available until run time