Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the location (src) of a javascript file?

Tags:

javascript

How can a javascript file know where it is located? For example:

<script type="text/javascript" src="http://mysite.com/scripts/howdy.js"></script>

How can the code in howdy.js know about http://mysite.com/scripts/howdy.js?

Edit: Clarification. I cannot rely on searching the DOM for my script tag because I need to know about it before the DOM may be ready.

like image 938
Josh Johnson Avatar asked Aug 23 '10 15:08

Josh Johnson


3 Answers

In the moment in which the current script is being executed, will be the last script element in the DOM, therefore you can get it by:

var scripts = document.getElementsByTagName('script'),
    currentScriptSrc = scripts[scripts.length-1].src;

Check this example that loads this script.

Edit: Taking in consideration the @kangax's comment, about the async and defer attributes, the only safe way IMO, previously knowing the file name, would be to inspect the script elements on the page, examining its src attribute, some libraries like Scriptaculous.us use this technique, for example:

var scripts = document.getElementsByTagName('script'),
    len = scripts.length,
    re = /howdy\.js$/,
    src, howdyScriptSrc;

while (len--) {
  src = scripts[len].src;
  if (src && src.match(re)) {
    howdyScriptSrc = src;
    break;
  }
}
​
like image 112
Christian C. Salvadó Avatar answered Sep 20 '22 04:09

Christian C. Salvadó


Give this script tag an id, and write:

var src = document.getElementById('scriptID').attributes['src'];
like image 36
Amr Elgarhy Avatar answered Sep 20 '22 04:09

Amr Elgarhy


Try this:

function getScriptSourceName(name){
    var scripts = document.getElementsByTagName('script');
    for (i=0;i<scripts.length;i++){
        if (scripts[i].src.indexOf(name) > -1)
            return scripts[i].src;
    }
}

getScriptSourceName('howdy.js');
like image 38
NicolasT Avatar answered Sep 20 '22 04:09

NicolasT