首页 > 代码库 > 关于页面reflow

关于页面reflow

什么是 reflow

浏览器为了重新渲染部分或整个页面,重新计算页面元素位置和几何结构(geometries)的进程叫做 reflow。

某个节点reflow时会重新计算节点的尺寸和位置,而且还有可能触发其子节点、祖先节点和页面上的其他节点reflow,在这之后再触发一次repaint。

由于 reflow 是一种浏览器中的用户拦截(user-blocking)操作,所以了解如何减少 reflow 次数,及不同的文档属性(DOM 层级(DOM depth),CSS 效率,不用类型的 style 变化)对 reflow 次数的影响对开发者来说非常必要。

 

引发 reflow 的一些因素:

  1. 调整窗口大小(Resizing the window)

  2. 改变字体(Changing the font)

  3. 增加或者移除样式表(Adding or removing a stylesheet)

  4. 内容变化,比如用户在input框中输入文字(Content changes, such as a user typing text in an input box)

  5. 激活 CSS 伪类,比如 :hover (IE 中为兄弟结点伪类的激活)(Activation of CSS pseudo classes such as :hover (in IE the activation of the pseudo class of a sibling))

  6. 操作 class 属性(Manipulating the class attribute)

  7. 脚本操作 DOM(A script manipulating the DOM)

  8. 计算 offsetWidth 和 offsetHeight 属性(Calculating offsetWidth and offsetHeight)

  9. 设置 style 属性的值 (Setting a property of the style attribute)

  10. 未指定图片宽高,载入时会使页面reflow

 

对于减少 reflow 优化性能的建议:

  1. 如果想设定元素的样式,通过改变元素的 class 名 (尽可能在 DOM 树的最里层)(Change classes on the element you wish to style (as low in the dom tree as possible))

  2. 避免设置多项内联样式(Avoid setting multiple inline styles)

  3. 应用元素的动画,使用 position 属性的 fixed 值或 absolute 值(Apply animations to elements that are position fixed or absolute)

  4. 权衡平滑和速度(Trade smoothness for speed)

  5. 避免使用 table 布局(Avoid tables for layout)

  6. 避免使用CSS表达式 (仅 IE 浏览器)(Avoid expressions in the CSS (IE only))

  7. 减少不必要的 DOM 层级(DOM depth)。改变 DOM 树中的一级会导致所有层级的改变,上至根部,下至被改变节点的子节点。这导致大量时间耗费在执行 reflow 上面。

  8. 尽量减少 CSS 规则,去除未用到的 CSS。

  9. 如果做复杂的表现变化,如动画,让它脱离文档流。用绝对定位或 fixed 定位来完成。

  10. 避免不必要的复杂的 CSS 选择器,尤其是后代选择器(descendant selectors),因为为了匹配选择器将耗费更多的 CPU。