JavaScript Includes And Rewritten URLs
Wednesday, 19th May 2010
I recently answered a question on a forum about JavaScript includes in ASP.NET MVC and as the question came up again today, I thought I'd share the answer with the world.
The issue that people are coming up against is that they have a script include with a relative path to their script file. Because ASP.NET MVC uses URL routing, the browser will treat the relative path differently depending on your current location. Here's a quick example...
You have referenced a script as you normally might, like this.
<script src="Scripts/MyScript.js" type="text/javascript"></script>
On your average web page, this works just fine. The problem is, this same script reference could appear on "www.stevefenton.co.uk" or it could appear on "www.stevefenton.co.uk/MyController/" or even "www.stevefenton.co.uk/MyController/MyAction/". In this last case, the browser would be looking for the script located at "www.stevefenton.co.uk/MyController/MyAction/Scripts/MyScript.js" and it isn't there.
This is a really easy problem to solve, using a quick and sly bit of "Url.Content", as demonstrated below.
<script src="<%= Url.Content("~/Scripts/MyScript.js") %>" type="text/javascript"></script>
Please note! I also work on quite a few PHP websites that utilise the Apache mod_rewrite engine, which performs a similar role to ASP.NET MVC routing. In the case of a PHP website, you can use the following fix... take note of the leading slash, which advises the browser that the path is relative to the root of the website.
<script src="/Scripts/MyScript.js" type="text/javascript"></script>
You Are Here: Home » Blog » JavaScript Includes And Rewritten URLs