Failed to execute 'write' on 'Document'js不能执行write浏览器报错

2019-08-31
0评论
/
阅读
爱搜啊

添加第三方统计代码发现Chrome浏览器报错,chrom报错:Failed to execute 'write' on 'Document': It isn't possibl,经过百度翻译发下这句话的意思是异步加载

Document已经加载解析完毕,文档流已经关闭了

所以你异步加载的js不可以再往document里写东西了,比如使用document.write

看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.

以前讲过如何修改好搜360自动收录js代码报错

好搜360搜索自动收录js代码报错

引起chrome报错的原因

document已经加载解析完毕,文档流已经关闭了

所以你异步加载的js不可以再往document里写东西了,比如使用document.write

不过你可以用dom方法添加

.appendChild()

.insertBefore()

.innerHTML

1、你可以把script加载放在body标签结束之前

2、如果你使用jquery,

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

统计代码一般都是直接一个标签,插入js,标签放在哪里,统计图表就放在哪里!

我现在是稍微改了一下,我自己加了一点js,在页面所有元素都加载完成之后我再动态的把统计js插入到我需要的地方。

统计代码的script是插入成功了,也加载成功了

今天添加第三方统计代码,发现,浏览器报错:

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. 

并没有达到如期效果。

百思不得骑姐啊。

对比下官方代码,我加了 defer='defer' 或者 async='async',

不想让js阻塞主流程。就是这点点差别,就出现如此情况。

把异步加载,取消,发现,可以了。

其实,看提示结果,也可以看出啊。

It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened

chrom报错:Failed to execute 'write' on 'Document'解决方法

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


本站附件分享,如果附件失效,可以去找找看

诚通网盘附件百度网盘附件


于2019-08-31发布
相关文章