views:

75

answers:

0

Hey all, I've been trying to throw together a generic function that retrieves the absolute URL of an executing JavaScript file on a web page:

http://gist.github.com/433486

Basically you get to call something like this:

getScriptName(function(url) {
    console.log(url);
    // http://www.example.com/myExternalJsFile.js
});

inside an external JavaScript file on a page and can then do something with it (like find the <script> tag that loaded it for example).

It works great in almost all the browsers I've tested (Firefox, Chrome, Safari, Opera v10 at least, and IE 8).

It seems to fail, however, in IE 6 and 7. The callback function gets executed, but the retrieved name is the URL to the main HTML page, not the JavaScript file. Continuing with the example, getScriptName invokes the callback with the parameter: http://www.example.com/index.html

So all I'm really asking is if there's some other way of getting the URL of the current JavaScript file (which could be IE 6 and 7 specific hackery)? Thanks in advance!

EDIT: Also, this won't work in every case, so please don't recommend it:

var scripts = document.getElementsByTagName("script");
return scripts[scripts.length-1].src;

I'd like it to work in the case of dynamically created script tags (possibly not placed last in the page), aka lazy-loading.