September 16, 2010
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.
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...
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
<script> tag manually declared. If you dynamically inject your
<script> tags programmatically, then the above technique doesn't work correctly. For my scenario to work, I had to tweak the solution a little bit.
Fortunately, I knew what file I was in, so I could do some partial matching to grab the script tag on the page to look at the src.
alert( $("script[src*=sourcefile1.js]").attr("src") );
The above code depends on jQuery, but I already have it loaded by this point, so it works out fine ;)
Thanks to everyone who helped me along in this fun and interesting problem.
Tweet about this post and have it show up here!