Rachit's Blog (Moved)
Moved to http://weblogs.asp.net/rachit

Adding Javascript file link in Master Page

Sunday, January 14, 2007 9:58 PM
Adding a referece of Javascript files in Master Pages is a pain. Because the location of Javascript can be in directory, you can simply write this:

<script type="text/javascript" src="../Scripts/some.js />
 
This will NOT work as when you deploy your site, it would depend on the directory structure.
Another problem is you also can NOT do the following:
 
<script type="text/javascript" src='<% = ResolveUrl("~/Scripts/some.js") %>' />

because Master Page won't allow any server-side tags.
The ultimate solution to this I found, is, as follows:

protected void Page_Load(object sender, EventArgs e)
{
  Page.ClientScript.RegisterClientScriptInclude("somescript", ResolveUrl("some.js"));
}


which produces the result

<script src="/Test1/some.js" type="text/javascript" />
 
Perfect! If you have a better solution, please add in the comments section. I'm definitely interested.

 

Update (01/28/2007):

Simon drew my attention that my technique above will add the JavaScript file to the < BODY > section of the page. In some cases, you don't want that. Here is my solution to add Javascript file to the < HEAD / > part. Thanks Simon.

HtmlGenericControl myJs = new HtmlGenericControl();
myJs.TagName = "script";
myJs.Attributes.Add("type", "text/javascript");
myJs.Attributes.Add("language", "javascript"); //don't need it usually but for cross browser.
myJs.Attributes.Add("src", ResolveUrl("some.js"));
this.Page.Header.Controls.Add(myJs);