【问题标题】:Incomplete HTML after Executing `document.write()`执行`document.write()`后不完整的HTML
【发布时间】:2016-02-23 22:34:20
【问题描述】:

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


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

【问题讨论】:

    标签: javascript jquery html overwrite document.write


    【解决方案1】:

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

    【讨论】:

      【解决方案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?为什么不直接将其添加为 HTML 上的&lt;script&gt;

      【讨论】:

        【解决方案3】:

        我认为您根本不想使用 document.write。您可以使用以下内容。制作一个 script 元素,并将其附加到 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)
        

        【讨论】:

          猜你喜欢
          • 2012-11-19
          • 2023-03-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-20
          • 1970-01-01
          • 2023-03-11
          相关资源
          最近更新 更多