重温Reflow

随着PC硬件性能的提升以及浏览器的性能提高,现在很少在意reflow相关的性能问题,甚至一度把它遗忘了;直到工作重心转向移动web开发,因为移动设备的CPU、内存等硬件资源非常有限,再加上频繁的操作DOM以及加入动画效果,才认识到reflow性能优化是非常必要的,所以再次阅读了reflow的相关资料并做了些归纳。

什么是 reflow
浏览器为了重新渲染部分或整个页面,重新计算页面元素位置和几何结构(geometries)的进程叫做 reflow。
由于 reflow 是一种浏览器中的用户拦截(user-blocking)操作,所以了解如何减少 reflow 次数,及不同的文档属性(DOM 层级(DOM depth),CSS 效率,不用类型的 style 变化)对 reflow 次数的影响对开发者来说非常必要。有时 reflow 页面中的一个元素会 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的 JavaScript 表达式 (仅 IE 浏览器)(Avoid JavaScript expressions in the CSS (IE only))
  7. 减少不必要的 DOM 层级(DOM depth)。改变 DOM 树中的一级会导致所有层级的改变,上至根部,下至被改变节点的子节点。这导致大量时间耗费在执行 reflow 上面。
  8. 尽量减少 CSS 规则,去除未用到的 CSS。
  9. 如果做复杂的表现变化,如动画,让它脱离文档流。用绝对定位或 fixed 定位来完成。
  10. 避免不必要的复杂的 CSS 选择器,尤其是后代选择器(descendant selectors),因为为了匹配选择器将耗费更多的 CPU。

相关资料
Reflows & Repaints: CSS Performance making your JavaScript slow?
Notes on HTML Reflow
形象化的reflow

This entry was posted in HTML & CSS. Bookmark the permalink.

2 Responses to 重温Reflow

  1. 电脑租赁 says:

    还是不太懂;;;

  2. 电动叉车 says:

    看你网站这个模板不错
    可能提供给大家下载啊?

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>