4

有没有办法找到当前运行脚本的来源?我想根据脚本的加载位置添加不同的行为。

例如从以下位置加载:

http://localhost:8080/js/myscript.js 

对比

http://www.myhost.com/js/myscript.js

我不是加载的人,所以我无法在加载时添加一些信息,并且脚本是使用动态加载的$.getScript(),所以我无法查找元素。

4

3 回答 3

6

调用脚本时,除非它被标记为deferor async,否则它将始终是该时刻页面上的最后一个元素(因为它是阻塞的)。

使用它,您可以执行以下操作:

var scripts = document.getElementsByTagName('script'),
    mylocation = scripts[scripts.length-1].getAttribute("src");

然后随心所欲地去做。

于 2013-08-15T12:04:35.780 回答
2

嗯..,它的一种黑客..!

首先,您需要获取所有脚本元素

var all_scripts = document.getElementsByTagName('script');

选择当前脚本

var current_script = all_scripts[all_scripts.length-1];

现在可以看到脚本的src了

alert(current_script.src);
于 2013-08-15T12:08:32.093 回答
-3

var o = $(this)根据@FelixKling 的建议删除了更新 的更改

更新示例

$.getScript("http://localhost:8080/js/myscript.js")
    .done(function(data, textStatus, jqxhr) {

        // this.url is the script url passed to $.getScript
        if(this.url.search('http://localhost:8080') != -1){
            alert("do one thing for http://localhost:8080/js/myscript.js");
        }
        if(this.url.search('http://www.myhost.com') != -1){
            alert("do another thing for http://www.myhost.com/js/myscript.js");
        }
    })
    .fail(function(){
        alert("somethign went wrong");
    });

Example on jsFiddle

于 2013-08-15T12:25:57.997 回答