Absolute or Relative URL issues and the solution

This article demonstrates the issues occur due to the usage of relative URLs while shifting pages from one location to another or the misuse of relative URLs and how to overcome those issues.

Relative URLs examples:
/* HTML example */
<img src="image.jpg" />

/* CSS example */
    background-image: url(image.jpg);

/* JavaScript example */
image.src = 'image.jpg';

Relative URLs and expected issues
In simple words, relative URL reference link on the same server (or domain).
  • <img src="image.jpg" /> Reference of a resource from same directory

  • <img src="../../image.jpg" /> In CSS/HTML, ../ used to reference parent directory. In the above example, ../ is used two times; so it is referencing a resource from 2-level parent directory.

  • <img src="sub-directory/image.jpg" />
    Reference of a resource from sub directory
The issue occurs when when shifting a page from one location to another which cause broken links.

/ and ../ are two different things:
  • <img src="/image.jpg" />
    Reference of a resource from root directory
  • <img src="../image.jpg" />
    Reference of a resource from 1-level parent directory

  • <img src="image.jpg" />
    Reference of a resource from same directory
Absolute URLs: The solution or ...
Absolute URLs solves most of relative URLs issues and also helps prioritized your website (SEO!). Absolute URLs also help testers or late-viewers to understand (+access) the located resource easily.

In JavaScript, we can create a global variable to store domain (root) URL:

/* Global variable */
var domainName = location.protocol + '//' + location.host;

/* Usage */
image.src = domainName + '/image.jpg';

JAMES PADOLSEY way of getting a fully qualified (absolute) URL in JavaScript:

function qualifyURL(url) {
    var img = document.createElement('img');
    img.src = url; // set string url
    url = img.src; // get qualified/absolute url
    img.src = null; // no server request
    return url;
// Tested successfully in IE6/7, FF2/3, Safari3, Opera9, Chrome (All on Windows XP) 

var myRelativeURL = 'blah/page.html';
alert( qualifyURL(myRelativeURL) );

Absolute URLs are helpful when shifting a page from one location to another because you don't have to change resource's URLs from within the shifted page.

A good link for parsing or making absolute URLs in JavaScript: https://gist.github.com/1088850

Protocol Level URLS:
<script src="//www.google.com/js/gweb/analytics/autotrack.js"></script>
<img src="//domain/image.jpg" />
Omitting the protocol—which makes the URL relative—prevents mixed content issues and results in minor file size savings.

No comments:

Post a Comment