tags:

views:

48

answers:

2

So, let's say I have this in the file http://site1.com/index.html:

<script src=http://site2.com/myscript.js&gt;&lt;/script&gt;

Inside "myscript.js", I need to get access to the URL "http://site2.com/myscript.js". I'd like to have something like this:

function getScriptURL() {
    // something here
    return s
}

alert(getScriptURL());

Which would alert "http://site2.com/myscript.js" if called from the index.html mentioned above.

I need this because the same script is going to be all over the place, and I don't want to have to hard-code its location into each one.

Thanks!

+2  A: 

Can't you use location.href or location.host and then append the script name?

Paul
That won't work, because the script is running within the http://site1.com/index.html page. So, even through the script is loaded from site2.com, if you access location from within the script, it will return "http://site1.com/index.html"...
Mike
A: 

From http://feather.elektrum.org/book/src.html:

var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];

The variable myScript now has the script dom element. You can get the src url by using myScript.src.

Note that this needs to execute as part of the initial evaluation of the script. If you want to not pollute the Javascript namespace you can do something like:

var getScriptURL = (function() {
    var scripts = document.getElementsByTagName('script');
    var index = scripts.length - 1;
    var myScript = scripts[index];
    return function() { return myScript.src; };
})();
lambacck
Will this always return the URL of the right script though, in all browsers? This looks like it will return the last script tag, but what if the document has more than one script tag in it?
Mike
The code needs to run in the global context of the script and then you need to cache the value somewhere if you need it later on in the script. If you are using the module pattern to do information hiding, your getScriptURL function could be defined in each script.
lambacck
Ok...my question then becomes, do all browsers always fully load an execute the complete contents of a remote script before moving on to the next script tag? How rigorously is this standardized? I could imagine it happening in parallel...
Mike
It is required that scripts run completely and in order because of what would happen if the script tag contained a document.write. This is the reason for the recommendations to put scripts at the bottom of the page because they will actually block other content from loading. That said, HTML5 modifies that with the use of the async and defer attributes: http://www.whatwg.org/specs/web-apps/current-work/multipage/scripting-1.html#script
lambacck
Further to the scripts at bottom, here is the Yahoo! best practices on that: http://developer.yahoo.com/performance/rules.html#js_bottom
lambacck