Thursday, July 29, 2010

Resolving relative URL's in javascript

In ASP.Net we have Page.ResolveUrl() method to resolve any relative URLs like "~/images/logo.gif". This at runtime renders the complete hosted path of the image e.g. http://Hostname/VirtualDirectory/images/logo.gif. This makes our applications safely deployable to virtual directories within IIS applications without messing up the URL's.

However, with javascript we don't have such an straight forward solution. One scenario where you might face such an problem of incorrect URL resolution is while using a single Master page for Web Content pages in different directories(root and sub directories).
So here's a little tweak that can be used with javascript to resolve the URL's at runtime:

Put below javascript in either the site's Master page or if you are not using Master page, put it in the first js file thats included in the page or in the first script section of the page:

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, this function can be use on any page that has reference of above script to resolve a relative url as show below:

var logoUrl = $Url.resolve("~/images/logo.gif");

Although, this solution is ASP.Net specific, but it can be used in any scripting language like php, jsp, etc by simply replacing the part "ResolveUrl("~/")" from above script to respective language's equivalent code.