>
 



The build in Page.ClientScript object allows you to place JavaScript inside an ASP.NET page. We cannot use this object to place JavaScript code or JavaScript include file into the head section of the page.

With ASP.NET 2.0, Visual Studio 2005 automatically places the runat="server" attribute  in the head tag of each page which allows us to interact with the page header.

You may add JavaScript code inside the page header with the following code block:

HtmlGenericControl include = new HtmlGenericControl("script");
include.Attributes.Add("type", "text/javascript");
include.InnerHtml = "alert('Hello World');";
this.Page.Header.Controls.Add(include);

And, you may add JavaScript include file inside the page header with the following code block:

HtmlGenericControl include = new HtmlGenericControl("script");
include.Attributes.Add("type", "text/javascript");
include.Attributes.Add("src", "/jsInclude.js");
this.Page.Header.Controls.Add(include);

Fortunately, Simone B created a library, to include/register scripts and style sheets into the head portion of an ASP.NET page.

HeadScriptManager Class Diagram
HeadScriptManager Class Diagram


In order to use the class library, reference the assembly, create an instance of HeadScriptManager and call its methods.

HeadScriptManager hm = HeadScriptManager.Current;
hm.RegisterHeadScriptResource(typeof(jTip), "jTip.jTip.js");

Source and binaries are available at sourceforge.net.

HeadScriptManager Sample Code
HeadScriptManager Sample Code

 

Currently rated 4.5 by 4 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5