Failed to execute 'write' on 'Document'動態載入的js不能執行write


統計代碼一般都是直接一個標簽,插入js,標簽放在哪里,統計圖表就放在哪里!

我現在是稍微改了一下,我自己加了一點js,在頁面所有元素都加載完成之后我再動態的把統計js插入到我需要的地方。

統計代碼的script是插入成功了,也加載成功了

現在問題來了………

看chrome的提示:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

這怎么回事,何解? 

如果你看到這段文字,說明您正使用RSS閱讀或轉自《一棵樹-博客園》,原文地址:https://www.cnblogs.com/atree/p/document-write-asynchronously-loaded.html 

 解決方法:

document已經加載解析完畢,文檔流已經關閉了

所以你異步加載的js不可以再往document里寫東西了,比如使用document.write

不過你可以用dom方法添加

.appendChild()

.insertBefore()

.innerHTML

1、你可以把script加載放在body標簽結束之前

例如:百度統計的統計代碼

<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?12356";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>

2、如果你使用jquery,也可以這樣:

$.getScript('[js containing the initialize function]',function(){
    $.getScript('https://maps.googleapis.com/maps/api/js?v=3.exp&callback=initialize');
}); 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM