如果对于 reflow 这个概念你还不太清楚或者不知道,请先阅读:

Yahoo! 性能工程师 Nicole Sullivan 在最新的文章 《Reflows & Repaints: CSS Performance making your JavaScript slow?》 中总结了导致 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)

reflow 会引起开销,影响页面的性能,那如何才能做到合理的优化呢?Nicole Sullivan 也提供了部分建议:

  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))

详细阅读:



共有11 条评论

  1. 1. 头像 lanqy

    感谢分享!

  2. 2. 头像 birdstudio

    谢谢分享~~

    另有翻译建议:

    as low in the dom tree as possible
    尽量在 DOM 树的最底层(末端)

    Trade smoothness for speed
    牺牲流畅度来换取速度

  3. 3. 头像 怿飞

    @birdstudio 不错的建议,thx

  4. 4. 蹲乐 UED » Blog Archive » 关于REFLOW

    [...] 转自:这里 上一篇: 创意别针 [...]

  5. 5. 头像 yoom

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

    一直这么干的,总感觉obj.style不够合理,特别是要同时更改多个样式的时候。

  6. 6. 头像 yoom

    看到淘宝,mozilla, yahoo的html代码都是做一个最外层的容器。
    or

    有什么好处呢,难道body不是天然的container或page么?总感觉这样会影响页面加载速度,因为它们的结束标签要到收尾阶段才能得到确认。

    或许是我还不理解浏览器的渲染流程

  7. 7. 头像 hax

    不想改obj.style的,可以改obj.currentStyle或getOverrideStyle

    个人经验觉得,reflow对于静态页面其实影响不大。只有要做动画的同志需要好好考虑一下。另,测试reflow的时间,可以用一个简单的方法:
    x.innerHTML = …
    t0 = new Date()
    x.offsetHeight
    t1 = new Date()
    alert(t1-t2)
    因为通常offsetHeight总是要等reflow完成才能计算出来,所以脚本会被阻塞直到reflow完成。

  8. 8. jsssc - 影响 reflow 的因素及其优化

    [...] 原文:http://www.planabc.net/2009/04/13/reflow/ [...]

  9. 9. 头像 天堂左我往右

    拖拽等交互看样子会很容易引起reflow…

  10. 10. 头像 text

    这个好厉害

  11. 11. Silentash-默尘 » DOM操作的性能优化

    [...] blog [...]

发表评论

(必填)

(必填,会为您保密)

评论仅支持“a、abbr、strong、em、blockquote、code”几个简单的标签