ASP.NET: Programmatically adding <script> tags to include JavaScript files in the master page’s <head> tag

One common task of ASP.NET master pages is the definition of the page’s <head> tag, which could include <script> tags to include external JavaScript files>. If you do not use absolute paths to refer to the JavaScript file, adding a <script> leads to the problem, that the path to the JavaScript file has to consider the directory structure.
Here is a simple code snippet that can be included in the master page’s code behind file to dynamically resolving the paths and adding the corresponding <script> tags:

protected void Page_Load(object sender, EventArgs e)
{
  [...]
  string[] jsFiles = {"~/Path/To/File1.js", "~/Path/To/File2.js"};
  foreach (var jsFile in jsFiles.Reverse()) // reverse the array to add <script> tags in the order the files are added to the array
  {
    var scriptTag = new HtmlGenericControl {TagName = "script"};
    scriptTag.Attributes.Add("type", "text/javascript");
    scriptTag.Attributes.Add("language", "javascript");
    scriptTag.Attributes.Add("src", ResolveUrl(jsFile));
    this.Page.Header.Controls.Add(scriptTag);
  }
  [...]
}

In the above example, you can use scriptTag.AddAt(index, scriptTag) to add the <script> tags at a specific position under the <head> tag.

Keep in mind, that ASP.NET provides other high level APIs to include custom JavaScript files inside the <form> tag with runat=server. If you rely on adding the <script> tag inside the <head> tag you can use the above example code, otherwise you can either use the ClientScriptManager

protected void Page_Load(object sender, EventArgs e)
{
  [...]
  Page.ClientScript.RegisterClientScriptInclude("File1", ResolveUrl("~/Path/To/File1.js"));
  Page.ClientScript.RegisterClientScriptInclude("File2", ResolveUrl("~/Path/To/File2.js"));
  [...]
}

or the ASP ScriptManager tag:

<asp:ScriptManager ID="ScriptManager1" runat="server">
  <Scripts>
    <asp:ScriptReference Path="~/Path/To/File1.js" />
    <asp:ScriptReference Path="~/Path/To/File2.js" />
  </Scripts>
</asp:ScriptManager>

Leave a comment

Your email address will not be published. Required fields are marked *

*