To dynamically add script tags to the head section of an HTML page based on conditions at page load use the following code.
This one adds a link to an external .js file:
if(UseUrchin)
{
HtmlGenericControl Include = new HtmlGenericControl("script");
Include.Attributes.Add("type", "text/javascript");
Include.Attributes.Add("src", "/__utm.js");
Page.Header.Controls.Add(Include);
}
This one adds actual JavaScript code inside the script tag:
if(UseUrchin)
{
HtmlGenericControl Include = new HtmlGenericControl("script");
Include.Attributes.Add("type", "text/javascript"); Include2.InnerHtml = "alert('We added it to the head');";
Page.Header.Controls.Add(Include);
}
Published by