简体   繁体   English

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

[英]Incomplete HTML after Executing `document.write()`

After executing document.write() , Google Chrome shows me that the HTML codes is changed from Code A to Code B . 执行document.write() ,谷歌浏览器向我显示HTML代码从代码A更改为代码B。 It seems that document.write() overwrite the entire page. 看来document.write()覆盖整个页面。 If yes, how to append the script tag inside head tag? 如果是,如何在head标签内附加script标签?


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

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


Code B : After Executing document.write() 代码B:执行document.write()

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


JavaScript in File .\\js\\main_CasCode.js 文件.\\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
}

That's because document.write erases and rewrites the document when the document has already finished rendering (like after onload ). 这是因为document.write在文档已经完成渲染后会擦除并重写文档(例如onload之后)。 It only appears to append when called during the rendering of the page. 它仅在页面呈现期间被调用时才显示追加。

A better way to do this is to dynamically create a script element, add it to the page, and add an src which triggers the loading mechanism. 更好的方法是动态创建脚本元素,将其添加到页面中,并添加一个触发加载机制的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';

In other news, why are you loading jQuery dynamically when you have control of the page? 在其他新闻中,为什么在控制页面后为什么动态加载jQuery? Why not add it directly as a <script> on the HTML? 为什么不将其直接添加为HTML上的<script>

I don't think you want to be using document.write at all. 我认为您根本不想使用document.write。 You can use the following. 您可以使用以下内容。 Make a script element, and append it to the head element 创建一个脚本元素,并将其附加到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)

document.write overwrites the whole DOM document.write覆盖整个DOM

You can create a function 您可以创建一个函数

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);  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM