Relative paths of images in JavaScript

There are three ways to specify a path to an image in html:

  • Completely relative: <img src="kitten.png"/>
  • Absolute with regard to the filesystem, but relative to the current server: <img src="/images/kitten.png">
  • Absolute in all respects: <img src="http://www.foo.com/images/kitten.png">

The second method may work for you.


Can't you just use a CSS class? If it's just a div containing an img, you can get rid of the img and use background-image on the div. Setting this from CSS will make sure that the image path is always relative to the CSS file and will almost certainly work no matter the environment (as long as the other images in your CSS work).

Then, you can just set the className on your div accordingly.


Mutable paths (test/staging/production domains) is always a problem in javascript, the best option is to include the root path of your application/website in the HTML. The obvious place to do this is in your template layer. For example:

<body data-root="${rootContext}">
<!-- or whatever syntax your template layer uses -->

And grab it with javascript for usage in your scripts.

var rootContext = document.body.getAttribute("data-root");

Note, you can only do this when the DOM is ready (or when document.body is available, differs cross browser) ;)

An alternative and in my view less pretty option is to simply render javascript.

<script>
    var rootContext = ${rootContext} // or whatever syntax your template layer uses.
</script>

At least with the 'data-root' technique, you can store the value wherever you like and avoid a global definition.

So in your code where you reference an image, you can do the following:

img.src = rootContext + "/media/js/close.gif";

Or create a nice helper method:

 // lets use a namespace to avoid globals.
 var myApp = {
     // still need to set this when DOM/body is ready
     rootContext: document.body.getAttribute("data-root"),
     getContext: function( src ) {
         return this.rootContext + src;
     }
 }

img.src = myApp.getContext( "/media/js/close.gif" );

In the helper method, you can also write some code to ensure proper uses of / and whatnot.