How might I get the script filename from within that script?

Solution 1:

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?

Solution 2:

I'm aware this is old but I have developed a better solution because all of the above didn't work for Async scripts. With some tweaking the following script can cover almost all use cases. Heres what worked for me:

function getScriptName() {
    var error = new Error()
      , source
      , lastStackFrameRegex = new RegExp(/.+\/(.*?):\d+(:\d+)*$/)
      , currentStackFrameRegex = new RegExp(/getScriptName \(.+\/(.*):\d+:\d+\)/);

    if((source = lastStackFrameRegex.exec(error.stack.trim())) && source[1] != "")
        return source[1];
    else if((source = currentStackFrameRegex.exec(error.stack.trim())))
        return source[1];
    else if(error.fileName != undefined)
        return error.fileName;
}

Not sure about support on Internet Explorer, but works fine in every other browser I tested on.

Solution 3:

You can use...

var scripts = document.getElementsByTagName("script"),
  currentScriptUrl = (document.currentScript || scripts[scripts.length - 1]).src;

currentScript() is supported by all browsers except IE.

Make sure it's ran as the file is parsed and executed, not on DOM ready or window load.

If it's an empty string, your script block has no or an empty src attribute.

Solution 4:

In Node.js:

var abc = __filename.split(__dirname+"/").pop();