On the server side of an ASP.NET or ASP.NET MVC application, we’re used to working with relative URL’s in the style of “~/Images/logo.png”. This makes our application safely deployable to virtual directories within IIS applications without messing up the URL’s. However, what do we do if we need the same functionality in our JavaScript?
I’m solving this by sticking the following script in my Site.Master file:
Url = function() { }
Url.prototype =
{
_relativeRoot: '<%= ResolveUrl("~/") %>',
resolve: function(relative) {
var resolved = relative;
if (relative[0] == '~') resolved = this._relativeRoot + relative.substring(2);
return resolved;
}
}
$Url = new Url();
Now, anywhere I need to resolve a relative url in a script, I can do this:
var logoUrl = $Url.resolve("~/Images/logo.png");