Linking to a JavaScript File from a ASP.NET Master Page (web forms)
So we have these big JavaScript functions in one of our MasterPages. I wanted to move them to a separate file but it proved more difficult than I thought!
I could not add a <link>
or <script>
tag to the get and use an application relative path such as ~/Scripts/MyScript.js"
.
Ended up just creating the control dynamically but it was interesting how I had to arrive to the right path. Here it is:
// Retrieve Header
HtmlHead header = (this.Page.Header as HtmlHead);
// If we have access of the page header:
if (header != null)
{
// Add script block for Master functions:
HtmlGenericControl scrptBlck = new HtmlGenericControl("script");
scrptBlck.Attributes.Add("src",
VirtualPathUtility.MakeRelative(
Request.AppRelativeCurrentExecutionFilePath,
"~/Scripts/MasterFunctions.js"));
scrptBlck.Attributes.Add("type", "text/javascript");
header.Controls.Add(scrptBlck);
}
Enjoy Reading This Article?
Here are some more articles you might like to read next: