Hi everyone, I tried to build a generic function that retrieves the absolute URL of a JavaScript executable on a web page:
http://gist.github.com/433486
Basically you call something like this:
getScriptName(function(url) { console.log(url);
inside an external JavaScript file on the page and then can do something with it (for example, find the <script> tag that loaded it, for example).
It works great in almost all the browsers I tested (Firefox, Chrome, Safari, Opera v10 at least and IE 8).
In IE 6 and 7, it does not seem to work. The callback function is executed, but the resulting name is the URL of the main HTML page, not a JavaScript file. Continuing the example, getScriptName calls the callback with the parameter: http://www.example.com/index.html
So, all I'm really asking about is there another way to get the URL of the current JavaScript file (which could be a specific IE 6 and 7 hacker)? Thanks in advance!
EDIT: Also, this will not work in every case, so please do not recommend:
var scripts = document.getElementsByTagName("script"); return scripts[scripts.length-1].src;
I would like it to work in the case of dynamically created script tags (possibly not placed last on the page), as well as lazy-loading.
javascript html cross-browser internet-explorer absolute
TooTallNate Jun 10 '10 at 10:50 2010-06-10 22:50
source share