2012-07-08 29 views
1

有没有办法加载一个js文件,里面有document.write?如何在createElement中使用document.write加载JavaScript文件?

即:

(function(){ 

    var test = document.createElement('script'); 
    test.type="text/javascript"; 
    test.src="http://xxxxxxxxxxx/test.js"; 
    document.getElementsByTagName('head')[0].appendChild(test); 

})(); 

test.js:

document.write('test !'); 

它总是返回有关文件撰写的异步警报错误...

我想通了,如果我这样做:

test.js:

document.getElementsByTagName('body')[0].innerHTML = 'test !'; 

它的工作原理!

但在我的情况下,我不能访问js文件,那么我想知道是否有办法做到这一点?或者我需要用php curl做一个交叉。

谢谢。

+0

在加载脚本之前,您可以尝试覆盖document.write函数。 – Bergi 2012-07-08 23:41:32

回答

3

document.write()设计用于解析文档时使用。如果您在加载文档后从动态加载的脚本中使用它,则会清除当前文档并开始编写一个全新的文档。

如果你想从内容动态加载脚本添加到当前文档,那么你应该使用DOM操作功能,如document.createElement().appendChild().insertBefore(),不document.write()

+0

+1 - 并进一步补充说明,OP应该阅读HTML5关于[document.write](http://www.w3.org/TR/html5/dynamic-markup-insertion.html#document.write ),指出它不是标准化的,仍然有很多实现依赖(HTML5基本上记录了现有的行为)。不过,我认为它会带来一些警告,如果使用得当,document.write *非常有用。 – RobG 2012-07-09 00:28:25

相关问题