reflow VS repaint

197 阅读2分钟

whats-the-difference-between-reflow-and-repaint

A repaint occurs when changes are made to an elements skin that changes visibly, but do not affect its layout.

Examples of this include outline, visibility, background, or color. According to Opera, repaint is expensive because the browser must verify the visibility of all other nodes in the DOM tree.

A reflow is even more critical to performance because it involves changes that affect the layout of a portion of the page (or the whole page).

Examples that cause reflows include: adding or removing content, explicitly or implicitly changing width, height, font-family, font-size and more.

简单理解,就是对于布局,也就是元素位置和大小有影响的就是 reflow,而如果仅仅是影响颜色、背景这种的就是 repaint,显然 reflow 对于渲染来讲成本更高,所以要尽量避免。这也就是为什么使用 transform 实现动画比控制 width, left 等这些值的动画更高效的原因。因为 transform 不会导致 reflow。

下面这张图也很有代表性,下面这张图是浏览器工作的流程。可以看到 layout 是在 paint 之前的,所以如果发生 reflow,流程会退回到 layout,然后继续 repaint,而如果只是 repaint 的话,就不会影响 layout 这一步,影响的链条要短一些。这也是为什么 reflow 比 repaint 更 expensive 的原因。

image.png

这篇文章里指出了一个常见的面试题: display: none 和 visibility: hidden 的区别。

Hiding DOM Element with display: none will cause both reflow and repaint Hiding DOM Element with visibility: hidden will cause the only repaint, because no layout or position change

The_stacking_context中说了:

Element with any of the following properties with value other than none: transform filter perspective clip-path mask / mask-image / mask-border

这也是为什么用 transform 的动画效果会好的原因,因为脱离了文档流,单独成为一层。不会影响整个页面的布局。

Element with a will-change value specifying any property that would create a stacking context on non-initial value (see this post).

关于 will-change 也可以看看这个内容