开发者

How to get the uri of the .js file itself

开发者 https://www.devze.com 2023-01-01 22:04 出处:网络
is there a method in JavaScript by which I can find out the path/uri of the executing script. For example:

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 va开发者_Python百科lue 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).


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;


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.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号