faqts : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

22 of 92 people (24%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

Can JavaScript get the filename of the file it's located in?

Apr 30th, 2008 17:06
Pete M, ha mo, Colin Fraser, Chris Kimball,


A previous poster suggested this was not possible; actually 
it is entirely possible by using a little DOM trickery. This is useful 
if the .js file needs to load other assets in the same directory as 
the js file, as opposed to being in the web root. 
Include the following snippet in the first line of your .js file:
var thisScript = (function(){
    var ScriptID = "ScriptID" + Math.round(100000*Math.random());
    document.write("<script id='"+ScriptID+"'></script>");
    return document.getElementById
(ScriptID).previousSibling.getAttribute("src");
})()
alert(thisScript);
and thisScript will contain a string representing the filepath to the 
currently-executing .js file, ie "JavaScript/test.js". If you are 
dealing with multiple JS files, just vary the name of thisScript, or 
else reference thisScript within a closure function to capture its 
state at the time it was executed.
Tested in IE 7, Firefox 2, Safari 3
HOW IT WORKS:
First off, we generate a random ID. Next, we use document.write to 
create a bogus <SCRIPT> tag in the DOM (we can't use DOM commands here 
because the page is still streaming and DOM doesn't fully exist)
That done, we now look for the bogus tag, knowing that its previous 
sibling *must* be the current <SCRIPT> tag. (Amazingly, even though 
DOM isn't fully written yet, this still works). Finally, we just grab 
the src attribute, and we have our answer.
I wrapped the whole thing in a null closure function, so the function 
and all variables it creates garbage-collect the moment it runs, to 
avoid stepping on any existing code. All that remains is the var you 
assigned along with its value.
MrHoo on Bytes suggested an even better way which avoids the horror of 
document.write and doesn't leave an artifact <SCRIPT>, although I 
haven't fully tested it yet: 
var theScript = (function(){
    var scr=document.getElementsByTagName('script');
    return scr[scr.length-1].getAttribute("src");
})();
alert(theScript);
I vaguely recall some problems in offname browsers with this approach, 
but it works fine in IE and Firefox