Dynamic Javascript Tag Insert – ASP.NET 2.0

A lot of JavaScript utilities need to be inserted at the bottom of the page so that the HTML elements that use them (or at least the function calls) do not generate errors. When using ASP.NET 2.0 master pages, you might want to insert the <SCRIPT> tags dynamically so that a particular JavaScript resource is available on every page.

I spent a lot of time trying to find a solution to this, and never really found a perfect one. The method I describe here is the best solution I could find at the moment.

Firts add a PlaceHolder Control, right before the end form tag. We’ll use this to write the <SCRIPT> tag so that it appears almost at the end of the document:

<asp:PlaceHolder ID=”plhJavaScript” runat=”server”></asp:PlaceHolder>

Then you can modify the master page’s Page_Load event to create a generic control, which will end up as the <SCRIPT> tag that is our goal. Once you have it, all you have to do is add it to the placeholder:

‘create generic html control

Dim JS As New HtmlControls.HtmlGenericControl(“script”)

JS.Attributes.Add(“type”, “text/javascript”)

JS.Attributes.Add(“src”, HttpContext.Current.Request.ApplicationPath & “/js/MyJavascriptFile.js”)

plhJavaScript.Controls.Add(JS)

That’s pretty much it. I think the code above might need tweaking to get the path always perfect if you’re down in a sub-directory, but you get the point.