Adding Elements to Head Tag In C#.NET

Monday, March 09, 2009

Here is a simple method to add Javascript (or any other code like CSS link tags) to the head of your HTML document using C#.
This will be useful if you want some script to be executed before the document starts loading (like initializing some Javascript globals).


HtmlHead head = Page.Header;

LiteralControl lctl = new LiteralControl("<script type='text/javascript'>"+
" /* Write your JavaScript Code here */"+
"</script>");

head.Controls.Add(lctl);

Although there are few other methods to do the same, this is one of the simplest and easy method I've found. You can place this code within the Page_Load function, or elsewhere you may want to.

0 comments:

Back to TOP