JavaScript Tip: Identify the location of a JavaScript file

This is a very short JavaScript tip.

Occasionally it is useful to obtain the path of a JavaScript file; for example, in order to refer to an image or other file which is located relative to your file.

Updated.

Suppose you have built a JQuery plugin or other JavaScript file, which requires a ‘loading’ animation; you might set a directory structure such as,

  • js/myfile.js
  • js/loading.gif

In order to locate the loading GIF you need to know the exact location of the JavaScript file, ‘myfile.js’

To do this, add the following to the top of the JavaScript file;

    var jsPath= document.scripts[document.scripts.length-1].src;
    if(jsPath.lastIndexOf('/')!=-1) {
        jsPath = jsPath.substring(0, jsPath.lastIndexOf('/')+1);
    }

This works because at the moment a script is loaded, it is the last script to appear in the document.scripts array.

Later, you can use the path, in this example to reference an image;

    var imgPath = jsPath+"/loading.gif";

Update:

I discovered that this does not work in Firefox, though it works fine in other browsers.

To get around it, I used a jQuery construct instead.

var jsPath = '';
if(typeof document.scripts != 'undefined') {
    jsPath = document.scripts[document.scripts.length-1].src;
} else {
    var srcArr = $('head script');
    jsPath = srcArr[srcArr.length-1].src;
}
I'd have preferred a non-jQuery solution, will add that in when I can!
blog comments powered by Disqus