tags:

views:

99

answers:

3

Hi, is there a method in JavaScript by which I can find out the path/uri of the executing script.

For example:

  1. index.html includes a JavaScript file stuff.js and since stuff.js file depends on ./commons.js, it wants to include it too in the page. Problem is that stuff.js only knows the relative path of ./commons.js from itself and has no clue of full url/path.

  2. index.html includes stuff.js file as <script src="http://example.net/js/stuff.js?key=value" /> and stuff.js file wants to read the value of key. How to?

UPDATE: Is there any standard method to do this? Even in draft status? (Which I can figure out by answers, that answer is "no". Thanks to all for answering).

+4  A: 

This should give you the full path to the current script (might not work if loaded on request etc.)

var scripts = document.getElementsByTagName("script");
var thisScript = scripts[scripts.length-1];
var thisScriptsSrc = thisScript.src;
Sean Kinsey
This (might) work (sometimes) if you only want to find out the URI for dynamically added scripts, but I doubt this is what he's looking for. In the case of dynamically added script elements, you might as well not bother with this and store the script URI before you create the script element in the first place.
Matti Virkkunen
What? This has nothing to do with dynamically added scripts. This has with how scripts are added to the DOM sequentially when parsed. And this does work.
Sean Kinsey
@Sean: Hum. Good point. Is this reliable across all the significant browsers? My original comment was kind of backwards, since this will certainly not work for dynamically added scripts, unless you always add them after any other script.
Matti Virkkunen
Yes, this is reliable as the spec states how scripts are parsed and added.
Sean Kinsey
+3  A: 

If your script knows that it's called "stuff.js", then it can look at all the script tags in the DOM.

var scripts = document.getElementsByTagName('script');

and then it can look at the "src" attributes for its name. Kind-of a hack, however, and to me it seems like something you should really work out server-side.

Pointy
This only works if the script is loaded via a script tag (and the tag is left in the DOM afterwards). Most script will be of course. But dynamically loaded code will have no such tags to go by.
Svend
+1  A: 

script.aculo.us (source) solves a similar problem. here is the relevant code

var js = /scriptaculous\.js(\?.*)?$/;
$$('script[src]').findAll(function(s) {
    return s.src.match(js);
}).each(function(s) {
    var path = s.src.replace(js, ''),
    includes = s.src.match(/\?.*load=([a-z,]*)/);
    (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
    function(include) { Scriptaculous.require(path+include+'.js') });
    }); 

(some parts of this like .each require prototype)

seanizer