我需要加载由 PHP 脚本生成的外部 JavaScript 文件,我还想将任何查询字符串参数传递给脚本,我想出了以下解决方案:
<script><br/>var url = 'http://example.com/scripts/js.php?foo=bar';<br/>url += location.search.replace(’?',’&’);<br/><br/>var s = document.createElement(’script’);<br/>s.setAttribute(’type’,'text/javascript’);<br/>s.setAttribute(’src’, url);<br/><br/>// get the script’s ‘outer html’ and add it to the document.<br/>var t = document.createElement(’div’);<br/>t.appendChild(s);<br/>document.write(t.innerHTML);<br/><br/></script>
这适用于除 IE 之外的所有浏览器(见图),我相信问题是生成的脚本还下载了更多 JS,这似乎挂起......有没有更好的方法来做这样的事情?
更新 如果我按 Ctrl + F5 加载页面,一切正常...这是为什么?脚本位于 http://example.com/scripts/js.php是一堆 document.write 调用。
最佳答案
您可以使用jQuery method 。 它易于使用且易于维护。
jQuery 适用于:IE 6.0+、FF 2+、Safari 3.0+、Opera 9.0+、Chrome
jQuery.getScript( url, [callback] )
Loads, and executes, a local JavaScript file using an HTTP GET request. Before jQuery 1.2, getScript was only able to load scripts from the same domain as the original page. As of 1.2, you can now load JavaScript files from any domain. Warning: In Safari version 2 and older it's not possible to evaluate scripts in a global context synchronously. If you load functions via getScript, make sure to call them after a delay.
示例:
$.getScript("test.js", function(){
alert("Script loaded and executed.");
});
关于javascript - 通过 JavaScript 将外部 JavaScript 文件添加到 DOM 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1555302/