Can a JavaScript file tell what URL requested itself?
16 Sep 2010I've been working on a project recently where I'm appending the current date to the end of script files so that they won't be cached.
I'm surrounding the code with lots of Unit Tests and I was trying to figure out the best way I could test that the script was actually loaded with the appended timestamp.
How could a JavaScript file tell what URL requested itself? Could the script know what URL make itself load?
Initially I was thinking location.href, but that ends up being the URL of the page the script was loaded on, not the script URL itself. Someone else suggested document.referrer, but that turns out to be the URL that referred the current page.
After a little time passed and several tweets passed by my stream, the correct answer flowed by...
Thanks to @cowboy @InfinitiesLoop @ashitvora for the answer and it is sooooo cleaver!
var scripts = document.getElementsByTagName( "script" );
var lastScript = scripts[scripts.length - 1];
alert( lastScript.src );β
Since the script files execute in order, if you grab the scripts on the document while you are executing, then the last script listed should be the one you are currently in!
This question has been asked on stackoverflow as well ;)
- How to get the file-path of the currenctly executing javascript code
- Can code in a Javascript file know its own domain/URL
As it turns out, the above technique only works for pages that have the