获取动态插入的当前js文件路径

时间:2015-01-30 14:17:44

标签: javascript

我已使用javascript(

)在http://example.com/index.html代码中创建了<script>代码
 (function() {
            var script_tag = document.createElement('script');
            script_tag.setAttribute("type","text/javascript");
            script_tag.setAttribute("src", "http://example2.com/xyz/def/internal.js");
            (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    })();

现在在这个internal.js文件中,我希望得到它的文件路径“http://example2.com/xyz/def/

1 个答案:

答案 0 :(得分:1)

Inside internal.js

var scripts = document.getElementsByTagName('script'),
    script = scripts[scripts.length - 1], url = "";
if (script.getAttribute.length !== undefined) {
   url = script.src;
}
else
{
   url = script.getAttribute('src', -1);
}

使用现代浏览器,这应该可行

url = document.currentScript.src;