9

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.

Josh Johnson
  • 10,729
  • 12
  • 60
  • 83
  • 2
    I'm curious, why do you need this info? – tenfour Aug 23 '10 at 15:13
  • possible duplicate of [How might I get the script filename from within that script?](http://stackoverflow.com/questions/710957/how-might-i-get-the-script-filename-from-within-that-script) – Marcel Korpel Aug 23 '10 at 15:13
  • 1
    @tenfour - There are other scripts that howdy.js may pull in from the same directory and I can't be certain where howdy.js will be hosted (test, prod, qa, client host, etc). It's not awesome but it is a business requirement. @Marcel - Yes, you are right, It is a dup. But I'll leave it up as I couldn't find that answer with the search terms I used. – Josh Johnson Aug 23 '10 at 15:21

4 Answers4

14

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;
  }
}
​
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
1

Give this script tag an id, and write:

var src = document.getElementById('scriptID').attributes['src'];
Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301
1

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');
NicolasT
  • 192
  • 4
0

Try:

document.scripts[document.scripts.length-1]; // add .src to get href
//or
document.getElementsByTagName("script")[document.getElementsByTagName("script").length-1];
//for (maybe) better compatibility

Which gets the last script in the DOM. If your script is being executed while it is being loaded, this will return the right element.

Save it to a variable for use in functions which will be used later.

var thisScript = document.scripts[document.scripts.length-1];
tcooc
  • 20,629
  • 3
  • 39
  • 57