62

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.

7
  • 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? Commented Apr 2, 2009 at 18:22
  • Yeah, that works, unless the filename is changed. I'm probably just being too pedantic. Commented Apr 2, 2009 at 18:24
  • Heh, if someone wants to submit "fuss less" and that gets a couple upvotes, I'd accept that as the answer. :D Commented Apr 2, 2009 at 18:26
  • 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. jibbering.com/faq/faq%5Fnotes/closures.html Commented Apr 2, 2009 at 18:30
  • 3
    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. Commented Oct 28, 2009 at 19:55

14 Answers 14

40
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?

Sign up to request clarification or add additional context in comments.

4 Comments

Edge case: If the current script was added to <head> after <body> is loaded and there are any scripts in <body> this will return the last script in the <body>, not the currently running script that's in <head>.
I have come across a case where this algorithm doesn't work reliably. Other script tags that are set to async can run between your script being requested and run. These scripts can add other scripts to the DOM which appear after yours. When your script run the last script on the page is no longer yours and the wrong src is returned.
This answer is seriously out of date. Scripts can be deferred, async, modules, workers. This answer works in none of them.
I feel like document.currentScript should be mentioned here, but like @gman said this answer is out of date overall and the algorithm does not cover many edge cases.
27

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.

11 Comments

Thanks! Exactly what I was looking for! Interesting that sometimes the same approach with error's stack appears in python or Java code.
Thanks! that's a great approach as it works also in Web Workers. However it fails after minification because the function is not called getScriptName anymore. The solution is to replace the currentStackFrameRegex expression with: new RegExp(arguments.callee.name + ' \(.+\\/(.*):\\d+:\\d+\)')
Very nice solution, sadly it does not work on IE10- :(
@PsychoWood I'll take a look and update the answer if I find a solution.
@MaMazav arguments.callee.name won't work If the function is defined as a function expression. I think the catch-all solution would be replacing arguments.callee.name with scriptName where scriptName is var scriptName = arguments.callee.name || 'getScriptName';. Of course, minification would change the variable name if the function expression is assigned to a normal variable, so one would have to assign the function to an object key to make this work.
|
23

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.

3 Comments

Not directly related to answer, but the famous caniuse.com doesn't monitor document.currentScript yet. An issue has been opened however. To make this feature appear on caniuse.com, you can vote up: github.com/Fyrd/caniuse/issues/1099.
I like that this is useful even in async scripts, unlike some other answers. Unfortunately, if currentScript is called in an event handler or global function that itself is called from another file, it will return that other file.
Further to the comment by @Stephan, there is now an entry for document.currentScript at caniuse.com.
10

In Node.js:

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

4 Comments

I tried this but I got __filename is not defined... am I using it wrong?
Apparently __filename and __dirname are node.js things, and only work in a node.js context.
@JoãoCiocca Adding to Alichino's comment the js client side cannot see the -server - filesystem whereas Node can. Thanks Alichino for thinking of the server side js.
You should add that abc first creates an array with two elements and then throws away the first element.
5

Shog9's suggestion more shorter:

alert("loading: " + document.scripts[document.scripts.length-1].src);

Comments

3

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
}

Comments

3

As the "src" attribute holds the full path to the script file you can add a substring call to get the file name only.

var path = document.scripts[document.scripts.length-1].src;

var fileName = path.substring(path.lastIndexOf('/')+1);

Comments

1

I had issues with the above code while extracting the script name when the calling code is included inside a .html file. Hence I developed this solution:

var scripts = document.getElementsByTagName( "script" ) ;
var currentScriptUrl = ( document.currentScript || scripts[scripts.length - 1] ).src ;
var scriptName = currentScriptUrl.length > 0 ? currentScriptUrl : scripts[scripts.length-1].baseURI.split( "/" ).pop() ; 

Comments

1

You can try putting this at the top of your JavaScript file:

window.myJSFilename = "";
window.onerror = function(message, url, line) {
    if (window.myJSFilename != "") return;
    window.myJSFilename =  url;
}
throw 1;

Make sure you have only functions below this. The myJSFilename variable will contain the full path of the JavaScript file, the filename can be parsed from that. Tested in IE11, but it should work elsewhere.

Comments

1

If you did't want use jQuery:

function getCurrentFile() {
    var filename = document.location.href;
    var tail = (filename.indexOf(".", (filename.indexOf(".org") + 1)) == -1) ? filename.length : filename.lastIndexOf(".");
    return (filename.lastIndexOf("/") >= (filename.length - 1)) ? (filename.substring(filename.substring(0, filename.length - 2).lastIndexOf("/") + 1, filename.lastIndexOf("/"))).toLowerCase() : (filename.substring(filename.lastIndexOf("/") + 1, tail)).toLowerCase();
}

Comments

0

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.

1 Comment

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. :)
0

The only way that is waterproof:

var code = this.__proto__.constructor.toString();
$("script").each(function (index, element) {
    var src = $(element).attr("src");
    if (src !== undefined) {
        $.get(src, function (data) {
            if (data.trim() === code) {
                scriptdir = src.substring(0, src.lastIndexOf("/"));
            }
        });
    }
});

"var code" can also be the function name, but with the prototype constructor you don't have to modify anything. This code compares its own content against all present scripts. No hard coded filenames needed anymore. Korporal Nobbs was in the right direction, but not complete with the comparison.

Comments

0

Using the javascript stack trace from Error object, you can extract the line 2 and do some substring and splits like below. The output will be the filename where the code is executed. This sample code assumes that you are executing on the same javascript. To determine the script that calls your script, you can try change the level to 2 like so. split('\n')[2]

let stack1 = new Error().stack.trim().split('\n')[1].trim()
console.log(stack1.substring(stack1.lastIndexOf('/')+1).split('?')[0])

Comments

0

I have found this method, which works pretty well. Let's say your js script filename is myScript.js. You can call this script from anywhere in your JS script, within or out of a function, e.g.

function anyfunction()
{
    const jsFilename = getCurrentScriptFileName();
    console.log("This JS filename is " + jsFilename);
}

function getCurrentScriptFileName()
{
    try{
        throw new Error();
    }
    catch(e){
        var stack = e.stack || e.stacktrace;
        var stackLines = stack.split("\n");
        var currentFile = stackLines[1].match(/(http[s]?:\/\/[^\s]+)/);
        
        if(currentFile){
            var currScript = currentFile[0];
        
            // currScript is now e.g.
            // "https://example.com/folder/myScript.js:82:35"
    
            const startIndex = currScript.lastIndexOf('/');
            const endIndex = currScript.indexOf(':', startIndex);
            const filename = currScript.slice(startIndex + 1, endIndex);
    
            // filename is now "myScript.js"
    
            return filename;
        }
        else return null;
    }
}

Then you'll get "myScript.js"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.