瀏覽器渲染流程
是否理解渲染流程通常無關緊要,但是在解決效能/進入頁面時閃爍這些問題時就很有必要理解他了。
瀏覽器建構物件模型
- Bytes received — 網路層接收 raw bytes
- Encoding detection — 確定字元編碼(UTF-8 等)
- Tokenization — HTML parser 將 byte stream 轉為 tokens(start tag、end tag、character、DOCTYPE 等)
- Tree construction — tokens 依 insertion mode 規則插入 DOM 樹;每次
insert a node觸發 custom element reactions(含connectedCallback入隊) - Microtask checkpoint — 在 tree construction 過程中的特定點執行,
connectedCallback實際在此執行 - Script execution — 遇到
<script>時,parser 暫停,JS engine 執行腳本(可能修改 DOM) - CSSOM construction — 平行下載並解析 CSS,建立 CSSOM(CSS Object Model)
- Render tree construction(Render Tree) — 合併 DOM + CSSOM,排除不可見節點(
display:none、<head>等) - Layout(Reflow) — 計算每個節點的幾何位置與尺寸
- Paint — 將各節點繪製為像素(顏色、文字、陰影等),產生 paint records
- Compositing — 將多個 layer 合成為最終畫面,輸出至螢幕
資訊來源:
Custom Element 的載入時機
Custom element 指的是自定義 HTML 元素,載入時機如上述的在 tree construction 時完成,因此最大的好處是畫面不閃爍,Astro Starlight 主題就使用 custom element 方案實現不閃爍的左側導航欄。
資訊來源:
- WHATWG DOM Standard - If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant, callback name "connectedCallback", and « ».
- WHATWG Custom elements - The way in which custom element reactions are invoked is done with special care, to avoid running author code during the middle of delicate operations. Effectively, they are delayed until "just before returning to user script". This means that for most purposes they appear to execute synchronously, but in the case of complicated composite operations (like cloning, or range manipulation), they will instead be delayed until after all the relevant user agent processing steps have completed, and then run together as a batch.
- WICG/webcomponents 規格討論
- SidebarPersister.astro
- SidebarPersistState.ts