与其通过附加脚本元素来加载脚本,不如通过 AJAX 调用加载脚本 URL 的内容,然后使用 eval() 在全局范围内运行它?这是一个示例,我确实对其进行了测试以验证它是否有效:
<!DOCTYPE html>
<html>
<head>
<script>
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
window.eval(xmlhttp.responseText); //Indirect call to eval to execute in global scope (http://perfectionkills.com/global-eval-what-are-the-options/)
}
}
xmlhttp.open("GET", "https://third-party.com/test.js", false); //This is synchronous so that any document.write calls don't overwrite the entire page when they get called after the document is finished rendering. For all intents and purposes, this just loads the script like any other script, synchronously.
xmlhttp.send();
</script>
</head>
<body>
<div><h2>Hello World</h2></div>
</body>
</html>
这是我在 test.js 文件中的内容:
document.write("This is a test...");
alert("...This is a test alert...");
console.log("...And a console message.");
我为脚本同步了 AJAX 请求,这样它就可以像普通的嵌入脚本标签一样被加载。如果您异步运行它,并且脚本在页面完全呈现后使用 document.write,它会清除 DOM 然后写入它......实际上有点烦人。让我知道这是否适合你。:)