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()


免責聲明!

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



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