首頁  >  文章  >  web前端  >  瀏覽器載入、渲染和解析過程黑箱簡析_javascript技巧

瀏覽器載入、渲染和解析過程黑箱簡析_javascript技巧

WBOY
WBOY原創
2016-05-16 17:47:361031瀏覽

用 Fiddler 監控,在 IE6 下,資源下載順序為:
ie6 timeline

很明顯,下載順序從上到下,文檔流中先出現的資源先下載。在 IE8, Safari, Chrome 等瀏覽器下也類似。

Firefox 對下載順序做了最佳化
firefox timeline
Firefox 會將 js, css 提前下載,而將圖片等資源延遲到後面下載。

對於渲染,利用 Fiddler 將網速調慢,可以看到 css 下載後會馬上渲染到頁面,渲染和下載同步進行。 js 的解析和運行,也類似。

對於 js 運行,以及頁面載入相關事件的觸發,特別做了測試。在 Firefox 下,開啟測試頁面:

[22:13:32.947] HTML Start[22:13:32.947] normal inline script run time[22:13:34.904] normal external script run time[22:13:35.775] [body] normal external script run time[22:13:35.789] [body end] normal external script run time[22:13:35.789] HTML End[22:13:35.791] deferred inline script run time[22:13:35.791] deferred external script run time[22:13:35.793] DOMContentLoaded[22:13:38.144] images[0] onload[22:13:38.328] images[1] onload[22:13:39.105] images[2] onload[22:13:39.105] images[3] onload[22:13:39.106] window.onload

很明顯,JS 的運作嚴格按照文檔流程的順序進行。其中 deferred 的腳本會在最後運行(註:Firefox 3.5 開始支援 defer,而且支援得很完美)。

再來看下 IE8,結果如下:

[22:33:56.806] HTML Start[22:33:56.826] normal inline script run time[22:33:57.786] normal external script run time[22:33:57.812] deferred inline script run time[22:33:57.816] document.readyState = interactive[22:33:57.934] [body] normal external script run time[22:33:58.310] [body end] normal external script run time[22:33:58.310] HTML End[22:33:58.346] deferred external script run time[22:33:58.346] images[0].readyState = loading[22:33:58.346] images[0].readyState = complete[22:33:58.346] images[0] onload[22:33:58.361] doScroll[22:33:58.451] images[1].readyState = loading[22:33:58.479] images[1].readyState = complete[22:33:58.479] images[1] onload[22:33:58.794] images[2].readyState = loading[22:33:58.854] images[2].readyState = complete[22:33:58.854] images[2] onload[22:33:58.876] images[3].readyState = loading[22:33:58.876] images[3].readyState = complete[22:33:58.876] images[3] onload[22:33:58.887] document.readyState = complete[22:33:58.888] window.onload

可以看出,IE8 下,defer 只對 external 腳本有效,對 inline 腳本無效。另,與 DOMContentLoaded 最接近的是 doScroll. 這是 doScroll 被廣泛用來模擬 DOMContentLoaded 的原因。小心:只是模擬,細節上並不等價。

還可以得到一個有點意外的結果:放在 body 結束前的腳本,執行時,依舊最好放在 domready 事件中。無論在 Firefox 或 IE 下,解析到 HTML End 時,並不代表 DOM 可以安全操作,特別是當頁面比較複雜時。

從上面資料中,也可以看出 YSlow 效能最佳化法則裡,建議將樣式置頂和腳本置底的根據。

有興趣的可以進一步測試動態添加樣式和腳本的情形,會稍有不同,但沒有特別 surprise.

最後總結下

頁面資源的下載順序是從上到下的,文檔流中先出現的資源先下載(註:存在並發,具體請參考 UA Profiler)。當某一樣式下載完成時,會立刻渲染到頁面(反映了層疊樣式表中層疊在渲染時的意義)。當某一腳本下載完成時,也會立刻解析並執行。腳本的運作嚴格按照文件流程中的順序進行,deferred 的腳本會在正常腳本運作之後執行(Firefox 和 IE 下)。

特別要留意:當腳本執行時,會暫停該腳本之下所有資源的下載(因為腳本可能改變文件流,甚至跳轉頁面,瀏覽器的暫停策略是合理的)。若要小心內嵌腳本,經常會阻塞後續下載。

好了,廢話不多說。以上結果,建議各位親自測試,反覆測試,瘋狂測試,一直到眼花繚亂稀里糊塗恍然大悟繼續糊塗為止……

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn