Relative URLs in Javascript - A Solution

I've previously written about absolute and relative paths in web development, and this follow-up post is here to show the method I've been using to get around the problem.

The secret sauce is the old HTML <base> tag. Simply output this in the <head> section of your template, with the href attribute set to the full URL of your site's root, then you can use a simple helper function like the one below to build full URLs in your javascript!

jQuery Example

function full_url(url) {
    // Get the base element.
    var base = $('base').attr('href');

    // Check the base URL has a trailing slash.
    if (base.substr(base.length -1) != '/') {
        base += '/';
    }

    // Ensure the URL we were passed doesn't have a leading slash.
    if (url.substr(0, 1) == '/') {
        url = url.substr(1);
    }

    return base+url;
}

If, like me, you use the excellent Kohana Framework, then all you need in your template is the following:

<base href="<?=url::base()?>">

Hey presto, simply use that function as a wrapper around root-relative URLs, and your site will work whether it's at the root or in a subdirectory, with no need to go through editing or hacking things.

Is that a better solution? Drop me a line over on Twitter with your comments and/or suggestions.