>>>Hi everybody,
>>>
>>>I'd like to add a global JavaScript to our Master page. In the Project I have JavaScript subfolder with some js files.
>>>
>>>My problem is that several pages are not in the root folder of the project but in their own subfolders.
>>>
>>>How should I reference the js file in the Master page to avoid the pathing problem?
>>>
>>>Thanks a lot in advance.
>>
>>Anyone has ideas here?
>>
>>Thanks again.
>
>You can just use the path relative to the root, ex.
>
>
><script type="text/javascript" src="/PathToJavaScriptFile.js" />
>
>
>Just be aware that if you move the site into a virtual directory that the path above will be incorrect, eg. you decide to host the site you've created in a virtual dir. named Site, ex.
>
>
http://www.mysite.com/Site>
>Now the path to the js file is incorrect, it should be /Site/PathToJavaScriptFile.js. According to the docs you can fix this pathing issue in most controls by using the tilde ~ in your path. In ASP.NET, that reference will get replaced with the application's virtual path (with server side controls).
>
>Normally that means you can do something like:
>
>
><img src="~/images/MyImage.jpg" runat="server" />
>
>
>or
>
>
><asp:Image id="imgSample" runat="server" ImageUrl="~/images/MyImage.jpg" />
>
>
>And ASP.NET will magically fix up the path. Unfortunately, external scripts things aren't quite as simple. The problem is that if you add a runat tag to this, ASP.NET will assume you are embedding code within the tags instead of referencing a JS file. Another way to do this would be something like this code:
>
>
><script type="text/javascript" src='< %=ResolveUrl("~/PathToJavaScriptFile.js") % >' />
>
>
>Or, if this is in a master page, like you're going to do, use a relative path from the master page to the JS file. So if you put the masterpage in the
>/Themes/MyTheme directory and the Javascript file was in /Script folder (both paths "relative" to the project), you would use:
>
>
><script type="text/javascript" src="../../Script/MyJavascriptFile.js" />
>
>
>As long as this is in the HEAD section of the master page, ASP.NET should fix it up for you.
Thanks a million for the explanation, Paul and for taking the time to answer this question. This is exactly how I have it set up already, but my colleague was saying it would not work this way.
If it's not broken, fix it until it is.
My Blog