使用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>
裏的腳本。app一、用戶處在弱網絡鏈接的環境下,特別是2G網絡。異步
二、document.write()在主頁面裏,對於那些嵌入在iframe裏的頁面沒有影響。async
三、在document.write()插入的腳本是阻礙解析的(parser-blocking)。若是插入的
<script>
標籤加了 'async' 或着'defer'屬性,腳本會異步加載,不影響解析 ,因此也是能被執行的。spa四、加載的腳本和站點不是同一個域名。code
五、腳本沒有在瀏覽器的緩存裏ip
六、頁面不是從新加載 從Chrome 53開始,對於知足2-5條件的代碼,在控制檯會輸出問題裏的警告:element
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.
解決方案:
一、最好的辦法就是不要使用
document.write()
動態加載腳本二、若是必定要使用
document.write()
加載腳本,使用異步加載的方式,如<scriptsrc="..."async>
或使用DOM APIelement.appendChild()