Tuesday, November 28, 2006

How to add JavaScript and CSS file declaration in ASP.NET 2.0 head tag

Code example in C# that show how to add JavaScript and CSS file declaration to ASP.NET runat server tag:

private const string JavaScriptIncludeTemplate = "script language='JavaScript' src='{0}' type='text/javascript' /script";

string includeLocation;
includeLocation = System.Web.VirtualPathUtility.ToAbsolute("~/JS/Test.js");

// Check that we have header runat=server on page
if ((System.Web.UI.HtmlControls.HtmlHead)Page.Header != null)
{
// Look if file declaration not already exist in page
if (((System.Web.UI.HtmlControls.HtmlHead)Page.Header).FindControl(key) == null)
{
LiteralControl include = new LiteralControl(String.Format(JavaScriptIncludeTemplate, includeLocation));
include.ID = key;

// Add the file declaration to page
// You can also use Controls.AddAt(addAt, include) to control the order of the JS file registration.
((System.Web.UI.HtmlControls.HtmlHead)Page.Header).Controls.Add(include);
}
}

1 comment:

Eran Sandler said...

I would add a check for Page.Header to see if its null or not.

I did run into more than a few occasion, mainly when developing a control, that it was placed on pages with no Header and therefore Page.Header returned null.