我想用javascript包含一个adserver js脚本并加载它async。但每次尝试都会以警告结束,并且脚本不会被执行。
我收到以下错误消息: "无法执行'写' on' Document':除非明确打开,否则无法从异步加载的外部脚本写入文档。"
我尝试过以下变体:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "http://example.com/test.js";
document.body.appendChild(script);
或者我使用HTML脚本属性async
<script src="http://example.com/test.js" async></script>
但没有任何效果,因为外部脚本使用document.write。还有其他方法来包含这样的脚本吗?
如何&#34;明确打开&#34;一个页面(&#34;除非明确打开&#34; - 见警告)?
答案 0 :(得分:1)
一种方法是暂时覆盖document.write
,直到执行脚本,然后替换原始功能。
var tempDocWrite = document.write;
document.write = function(el){
var div = document.createElement('div');
div.innerHTML = el;
document.body.appendChild(div)
}
var script = document.createElement('script');
script.onload = function(){
document.write = tempDocWrite
}
script.type = 'text/javascript';
script.src = "http://example.com/test.js";
document.body.appendChild(script);
注意:尚未测试上述代码