How to get uri of the .js file itself

Is there a JavaScript method in which I can find out the / uri path to execute the script.

For instance:

  • index.html contains the JavaScript stuff.js file, and since the stuff.js file depends on ./commons.js , it wants to include it on the page as well. The problem is that stuff.js only knows the relative ./commons.js path from itself and does not have the concept of a complete URL.

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

UPDATE: is there a standard method? Even in draft status? (What can I find out from the answers, this answer is “no.” Thanks everyone for the answer).

+4
source share
3 answers

This will give you the full path to the current script (may not work if loaded on demand, etc.)

 var scripts = document.getElementsByTagName("script"); var thisScript = scripts[scripts.length-1]; var thisScriptsSrc = thisScript.src; 
+5
source

If your script knows that it is called "stuff.js", then it can view all script tags in the DOM.

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

and then he can look at the "src" attributes for his name. However, the kind of hack, and for me it seems like you should really be working on the server side.

+3
source

script.aculo.us ( source ) solves a similar problem. here is the corresponding 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=([az,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) { Scriptaculous.require(path+include+'.js') }); }); 

(some parts of this type of .each require a prototype)

+1
source

Source: https://habr.com/ru/post/1311743/


All Articles