0

So I have a script that is loaded dynamically into the page as so:

<div>
    <script>
        var url = 'http://example.com/scripts/myscript.js?foo=bar';
        document.write('<scr'+'ipt type=\"text/javascript\" src=\""+url+"\"></scri'+'pt>')
    </script>;
</div>

I need to know, if there is a way, inside the myscript.js i am loading, to access the url to get the query string.

Thanks

4

1 回答 1

3

当脚本运行时(除非您添加deferasync属性),它始终是页面上的最后一个元素。因此,您可以利用这一事实:

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

然后,您可以处理该myScriptURL变量以提取查询字符串参数,如本问题所示

于 2013-11-07T14:06:42.310 回答