ASP.net Dynamic Script Loading in HTML Head

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);
      }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s