重绘与回流(repaint和reflow)

reflow:回流
回流:指计算页面布局。render tree中的一部分(或全部)因为元素的规模尺寸,布局,隐藏等改变而需要重新构建。这就称为回流,每个页面至少需要一次回流,就是在页面第一次加载的时候。
repaint :重绘
重绘:当render tree中的一些元素需要更新属性,而这些属性只是影响元素的外观,风格,而不会影响布局的,比如background-color。则就叫称为重绘。
导致回流
很多状况下都会导致回流:
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)
8. 设置 style 属性的值 (Setting a property of the style attribute)
什么情况下触发浏览器的repaint/reflow?
9. 页面首次加载时
10. DOM元素的添加、修改(内容)、删除( Reflow + Repaint)
11. 仅修改DOM元素的字体颜色(只有Repaint,因为不需要调整布局)
12. 应用新的样式或者修改任何影响元素外观的属性
13. Resize浏览器窗口、滚动页面
6.读取元素的某些属性(offsetLeft、offsetTop、offsetHeight、offsetWidth、scrollTop/Left/Width/Height、clientTop/Left/Width/Height、getComputedStyle()、currentStyle(in IE))
css避免回流,提升性能
1.尽可能在DOM树的最末端改变class
2.避免设置多层内联样式
3.动画效果应用到position属性为absolute或fixed的元素上
4.牺牲平滑度换取速度
5.避免使用table布局
6.避免使用CSS的JavaScript表达式
如何减小reflow
1. 减少不必要的 DOM 层级(DOM depth)。改变 DOM 树中的一级会导致所有层级的改变,上至根部,下至被改变节点的子节点。这导致大量时间耗费在执行 reflow 上面。
2. 尽量减少 CSS 规则,去除未用到的 CSS。
3. 如果做复杂的表现变化,如动画,让它脱离文档流。用绝对定位或 fixed 定位来完成。
4. 避免不必要的复杂的 CSS 选择器,尤其是后代选择器(descendant selectors),因为为了匹配选择器将耗费更多的 CPU。
参考文献:http://blog.csdn.net/oscar999/article/details/38379523

猜你喜欢

转载自blog.csdn.net/MingleHDU/article/details/76571532