A parser-blocking, cross site (i.e. different eTLD+1) script, is invoked via document.write

使用Chrome访问第三方的js库时,在控制台出现警告:

A Parser-blocking, cross-origin script, https://example.com/script.js, is invoked via document.write. This may be blocked by the browser if the device has poor network connectivity.

原因分析:

在弱的网络连接环境下,比如2G网络,在页面上使用document.write()来动态插入外部的脚本会阻塞页面的解析,延迟页面的显示,甚至加载脚本失败,最终导致页面不能正确显示。

什么条件下出现这种警告:

为了提高用户的体验,Chrome对于由document.write()动态插入的 <script>会做检查,当满足下面所有的条件下,Chrome不会执行加载 <script>里的脚本。

1、用户处在弱网络连接的环境下,特别是2G网络。

2、document.write()在主页面里,对于那些嵌入在iframe里的页面没有影响。

3、在document.write()插入的脚本是阻碍解析的(parser-blocking)。如果插入的 <script>标签加了 'async' 或着'defer'属性,脚本会异步加载,不影响解析 ,所以也是能被执行的。

4、加载的脚本和站点不是同一个域名。

5、脚本没有在浏览器的缓存里

6、页面不是重新加载 从Chrome 53开始,对于满足2-5条件的代码,在控制台会输出问题里的警告:

A Parser-blocking, cross-origin script, https://example.com/script.js, is invoked via document.write. This may be blocked by the browser if the device has poor network connectivity.

解决方案:

1、最好的办法就是不要使用 document.write()动态加载脚本

2、如果一定要使用 document.write()加载脚本,使用异步加载的方式,如 <scriptsrc="..."async> 或使用DOM API element.appendChild()

原文地址:https://www.cnblogs.com/myprogramer/p/11641566.html