如果你對 reflow 這個概念還不太清楚,建議先閱讀以下延伸資料:
- 《Notes on HTML Reflow》
- 《What is a reflow?》
- 《Gecko:Reflow Refactoring》
- 《reflow》
- 《形象化的 reflow》
- 《樣式的執行效率-reflow》
Yahoo! 效能工程師 Nicole Sullivan 在文章《Reflows & Repaints: CSS Performance making your JavaScript slow?》中,歸納了導致 reflow 發生的一些因素:
- 調整視窗大小(Resizing the window)
- 改變字型(Changing the font)
- 增加或移除樣式表(Adding or removing a stylesheet)
- 內容變化,例如使用者在 input 框中輸入文字(Content changes)
- 啟用 CSS 偽類,如 :hover(在 IE 中為啟用兄弟節點的偽類)
- 操作 class 屬性(Manipulating the class attribute)
- 腳本操作 DOM(A script manipulating the DOM)
- 計算 offsetWidth 和 offsetHeight 屬性
- 設定 style 屬性的值(Setting a property of the style attribute)
reflow 會帶來開銷、影響頁面效能,那該如何合理優化呢?Nicole Sullivan 也提供了部分建議:
- 想設定元素樣式時,透過改變元素的 class 名(盡量放在 DOM 樹的最內層)。
- 避免一次設定多項內聯樣式。
- 為元素套用動畫時,使用 position 的 fixed 或 absolute 值。
- 在平滑度與速度之間權衡取捨。
- 避免使用 table 排版。
- 避免在 CSS 中使用 JavaScript 表達式(僅 IE 瀏覽器)。
詳細閱讀:《Reflows & Repaints: CSS Performance making your JavaScript slow?》
原文:https://www.planabc.net/2009/04/13/reflow/