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>.
Tweet
2 comments:
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
:)
Abhishek: The advantage is in cases when your client script depends on information that is not available until run time
Post a Comment