执行 `document.write()` 后 HTML 不完整

Incomplete HTML after Executing `document.write()`

执行 document.write() 后,Google Chrome 显示 HTML 代码从 代码 A 更改为 代码B。似乎 document.write() 覆盖了整个页面。如果是,如何在head标签内追加script标签?


代码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
}

我认为您根本不想使用 document.write。您可以使用以下内容。制作一个脚本元素,并将其附加到头部元素

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)

这是因为 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?为什么不直接将其添加为 HTML 上的 <script>

document.write 覆盖整个 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);  
}