Can a JavaScript file tell what URL requested itself?

I'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 ;)

As it turns out, the above technique only works for pages that have the

If you enjoyed this post, please consider sharing it with others via the following Twitter or Reddit buttons. I also have a YouTube Channel with free web development videos that you are welcome to watch and/or subscribe. As always, you can reach out to me on Twitter at @elijahmanor. Thanks and have a blessed day!