65.9K
CodeProject is changing. Read more.
Home

Add Javascript inside head element of page from code behind

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Oct 11, 2013

CPOL
viewsIcon

13640

Howto: Add JavaScript inside Head element from code behind  Here is the sample how you can do that.1)  Add some JavaScript inside page header

Howto: Add JavaScript inside Head element from code behind 

 Here is the sample how you can do that.

1)  Add some JavaScript inside page header

protected void Page_Load(object sender, EventArgs e)
{
	System.Web.UI.HtmlControls.HtmlGenericControl si = new System.Web.UI.HtmlControls.HtmlGenericControl();
	si.TagName ="script";
	si.Attributes.Add("type",@"text\javascript");
	si.InnerText = @"alert('I am in Head Element.')";
	this.Page.Header.Controls.Add(si);
}
2)  Add .js file reference inside page header
protected void Page_Load(object sender, EventArgs e)
 {
	 System.Web.UI.HtmlControls.HtmlGenericControl si = new System.Web.UI.HtmlControls.HtmlGenericControl();
 	si.TagName ="script";
 	si.Attributes.Add("type",@"text\javascript");
 	si.Attributes.Add("src","util.js");
 	this.Page.Header.Controls.Add(si);