2015-11-21 31 views
-1

执行document.write()后,谷歌Chrome显示我的HTML代码从代码A改为代码B。看来,document.write()覆盖整个页面。如果是,如何在head标签内添加脚本标签?不完整的HTML()`


代码A:之前执行document.write()

<!--DOCTYE html--> 
<html> 
<head> 
    <script src=".\js\main_CasCode.js"></script> 
</head> 
<body onload="main()"> 
    <p>hi</p> 
</body> 
</html> 


代码B:执行document.write()

<html> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
</head> 
</html> 


后在JavaScript的文件.\js\main_CasCode.js

function main() { 
    //console.log = function() {}; 
    loadjQuery(); 
    //waitjQueryLoaded_and_start(); 
} 

function loadjQuery() { 
    console.log("Loading jQuery..."); 
    var s = '<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>'; 
    document.write(s); //<----Problem Here 
} 

回答

2

这是因为document.write擦除和重写当文档已经完成渲染(如onload后)的文件。它只在页面呈现期间被调用时才会附加。

更好的方法是动态创建脚本元素,将其添加到页面中,并添加触发加载机制的src

var script = document.createElement('script'); 
document.getElementsByTagName('head')[0].appendChild(script); 
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'; 

在其他消息中,为什么您在控制页面时动态加载jQuery?为什么不直接将它作为<script>添加到HTML上?

1

我不认为你想被使用document.write的。您可以使用以下内容。做一个脚本元素,而且它添加到head元素

var head = document.getElementsByTagName('head')[0] 
var s = document.createElement('script') 
s.src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" 
head.appendChild(s) 
1

文件撰写覆盖整个DOM

您可以创建一个功能

function loadjQuery() { 
    console.log("Loading jQuery..."); 
    var scrpt = document.createElement('script'); 
    scrpt.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js'; 
    document.head.appendChild(scrpt); 
}