How might I get the script filename from within th

2019-01-02 15:42发布

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.

11条回答
妖精总统
2楼-- · 2019-01-02 16:20

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);
查看更多
明月照影归
3楼-- · 2019-01-02 16:23

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.

查看更多
无色无味的生活
4楼-- · 2019-01-02 16:24

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();
}
查看更多
看淡一切
5楼-- · 2019-01-02 16:26

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
}
查看更多
若你有天会懂
6楼-- · 2019-01-02 16:29

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() ; 
查看更多
孤独寂梦人
7楼-- · 2019-01-02 16:34
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?

查看更多
登录 后发表回答