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

JavascriptHtml

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

In Node.js:

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

Solution 5 - Javascript

Shog9's suggestion more shorter:

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

Solution 6 - Javascript

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
}

Solution 7 - Javascript

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);

Solution 8 - Javascript

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() ; 

Solution 9 - Javascript

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.

Solution 10 - Javascript

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();
}

Solution 11 - Javascript

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.

Solution 12 - Javascript

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. https://stackoverflow.com/users/2703106/korporal-nobbs">Korporal Nobbs was in the right direction, but not complete with the comparison.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncoreView Question on Stackoverflow
Solution 1 - JavascriptShog9View Answer on Stackoverflow
Solution 2 - JavascriptjduncanatorView Answer on Stackoverflow
Solution 3 - JavascriptalexView Answer on Stackoverflow
Solution 4 - JavascriptAlichinoView Answer on Stackoverflow
Solution 5 - JavascriptF-3000View Answer on Stackoverflow
Solution 6 - JavascriptAlex RozanskiView Answer on Stackoverflow
Solution 7 - JavascriptKorporal NobbsView Answer on Stackoverflow
Solution 8 - JavascriptSandro RosaView Answer on Stackoverflow
Solution 9 - JavascriptjohnnydangerView Answer on Stackoverflow
Solution 10 - JavascriptJoseLazoView Answer on Stackoverflow
Solution 11 - JavascriptDisgruntledGoatView Answer on Stackoverflow
Solution 12 - JavascriptoyosoftwareView Answer on Stackoverflow