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

Published by

Unknown's avatar

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a comment