如何使用带有javascript的document.write加载脚本

时间:2013-06-19 20:29:29

标签: javascript ajax appendchild document.write

我想在装有AJAX / jQuery-JSON的页面中显示广告。

  • 剧本:
  • 文件xxxxx.js包含document.write();

如何集成此脚本并使document.write得到解释。 为什么它不起作用?

这里是我的测试显示脚本被执行是因为显示了警报('hello 1')但没有显示包含警报的document.write('hello 2');

直接将文件调用到DOM执行井“hello 1”和“hello 2”

test.js

alert("hello 1");
document.write('<scr'+'ipt type="text/javascript">alert("hello 2");</scr'+'ipt>');

索引:

<body>
<script>
function loadScriptJs() {
var s = document.createElement('script'); 
s.src = 'test.js';  
s.type = 'text/javascript';
document.getElementById("pub").appendChild(s);
}
</script>
<div id="pub">
    PUB A AJOUTER CI DESSOUS EN JAVASCRIPT  :
    <!--  appel direct de la pub 
    <script src="test.js" type="text/javascript"></script> -->
</div>
<script> loadScriptJs(); </script>
</body>

1 个答案:

答案 0 :(得分:1)

当您使用appendChild添加脚本时,它会异步加载。因此,当test.js中的代码运行时,可能已经构造了DOM,document.write将覆盖所有页面内容。

看起来最简单的解决方案是替换它:

<script> loadScriptJs(); </script>

使用:

<script src="test.js"></script>

另一个选择是不在test.js中使用document.write。从loadScriptJs开始,为脚本加载(s.onload = function() { /* loaded */ }))设置回调,然后从该回调中将广告注入DOM。