views:

144

answers:

4

I'm pretty sure the answer is no, but thought I'd ask anyway.

If my site references a scripted named "whatever.js", is it possible to get "whatever.js" from within that script? Like:

var scriptName = ???

if (typeof jQuery !== "function") {
    throw new Error(
     "jQuery's script needs to be loaded before " + 
     scriptName + ". Check the <script> tag order.");
}

Probably more trouble than it's worth for dependency checking, but what the hell.

+2  A: 

Since you are going to be typing that line into the file somewhere, couldn't you just type in the name of the file you're adding it to?

MarkusQ
Yeah, that works, unless the filename is changed. I'm probably just being too pedantic.
Chris
Heh, if someone wants to submit "fuss less" and that gets a couple upvotes, I'd accept that as the answer. :D
Chris
Specifying 'var scriptName = ...' inside each script probably isn't the greatest idea. The way you are declaring it, scriptName is a global variable. It would work better if you used closures. http://www.jibbering.com/faq/faq%5Fnotes/closures.html
Sebastian Celis
The other advantage to this is if you want to get the full URL-path to the running script. Not all .js files are served from the same domain as the html pages that use them.
Ed Brannin
+5  A: 
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
alert("loading: " + scriptName);

Tested in: FF 3.0.8, Chrome 1.0.154.53, IE6


See also: How may I reference the script tag that loaded the currently-executing script?

Shog9
+2  A: 

You can return a list of script elements in the page:

var scripts = document.getElementsByTagName("script");

And then evaluate each one and retrieve its location:

var location;

for(var i=0; i<scripts.length;++i) {
   location = scripts[i].src;

   //Do stuff with the script location here
}
Perspx
A: 

What will happen if the jQuery script isn't there? Are you just going to output a message? I guess it is slightly better for debugging if something goes wrong, but it's not very helpful for users.

I'd say just design your pages such that this occurrence will not happen, and in the rare event it does, just let the script fail.

DisgruntledGoat
Yes, I throw new Error() with a "include the script dumbass!" message. My feeling is that it's just good practice. People tend to slack on things like this because it's a dynamic language. I'll sleep better this way though. The extra 100 bytes are worth it to me. :)
Chris