使用 document.write()

使用 document.write() 可能會導致網頁內容延遲數十秒才顯示,對於連線速度較慢的使用者來說,更是問題重重。因此,Chrome 在許多情況下會封鎖 document.write() 的執行作業,也就是說,您無法依賴這項功能。

使用 document.write() 時,Chrome 開發人員工具控制台會顯示下列訊息:

[Violation] Avoid using document.write().

Firefox 開發人員工具控制台會顯示以下訊息:

An unbalanced tree was written using document.write() causing
data from the network to be reparsed.

Lighthouse document.write() 稽核失敗的原因

Lighthouse 會標示 Chrome 未封鎖的 document.write() 呼叫:

Lighthouse 稽核顯示 document.write 的使用情況

對於最容易造成問題的使用情形,Chrome 會視使用者的連線速度,封鎖對 document.write() 的呼叫或發出主控台警告。無論是哪種情況,受影響的呼叫都會顯示在開發人員工具控制台中。 詳情請參閱 Google 的「Intervening against document.write()文章。

無論如何使用,剩餘的 document.write() 呼叫都會對效能造成負面影響,而且有更好的替代方案,因此 Lighthouse 會回報這類呼叫。

建議不要使用 document.write()

移除程式碼中所有 document.write() 的用法。如果用於插入第三方指令碼,請改用非同步載入

如果第三方程式碼使用 document.write(),請要求供應商支援非同步載入。

資源