页面渲染——页面合成(composition)的优化

合成(composition)意味着将网页中已经绘画好的部分结合在一起,且展示在屏幕上。

  • 坚持使用transform和opacity属性来操作你的动画animation
  • 在有动画的元素上使用 will-change 或 translateZ属性
  • 不要为所有元素创建合成器层:layers需要内存和管理 

在合成领域有两个换件的因素将影响你的性能:

所需要处理的合成层的数量,动画时你使用的属性。

动画的改变使用transform和opacity属性。

对像素管道而言最好是避免layout和paint,只需要合成的改变。

The pixel pipeline with no layout or paint.

为了实现上面的效果,你应该坚持使用那些能被合成器直接处理的属性,现在只有两个属性能被合成器直接处理:transform和opacity。

The properties you can animate without triggering layout or paint.

唯一要注意的是,每当在元素上使用transform和opacity的时候都应该在元素独自的合成器层(compositor layer)使用。

为了确保这一点,你必须首先允许元素拥有合成器层。

Note

  • 如果你担心你的动画效果不能直接只使用这两个动画属性,那么检查 FLIP principle 网页,它会告诉你不同的复杂的动画效果怎样通过这两个基本的属性实现。

确保你的元素可以拥有合成器层

你应该在你要使用动画的元素上加上以下样式:

.moving-element {
  will-change: transform;
}

针对旧的浏览器:

.moving-element {
  transform: translateZ(0);
}

上面的代码将告诉浏览器我要进行动画了,浏览器会做一些准备,例如,创建一个合成器层。

管理layers

It’s perhaps tempting, then, knowing that layers often help performance, to promote all the elements on your page with something like the following:

* {
  will-change: transform;
  transform: translateZ(0);
}

为了节省起见,你可能会使用上面的代码为所有的元素创建合成器层,但是你要知道每一个层都是需要内存和管理的,对于低内存的设备这样做是不好的!所以,不要为那些没有必要的元素创建合成器层。

使用开发者工具了解你的应用中的layers

为了理解你的应用中的所有layer,以及为什么一个元素中有一个layer,你首先要在Timeline上允许Paint,如下:

The toggle for the paint profiler in Chrome DevTools.

首先你要开始记录(刷新页面开始记录)记录结束之后,你可以点击单独的帧。单独的帧是在时间和详细信息板块之间,如下:

A frame the developer is interested in profiling.

点击之后在最下面将会展示layer的tab选项

The layer tab button in Chrome DevTools.

允许你在每一帧上面的layer进行查看

The layer view in Chrome DevTools.

使用上面你可以追踪你有多少的layers。如果你在performance-critical动作(例如scroll和transitions)中耗费太多的时间来合成(你的目标是4-5毫秒),你可以查看你有多少layer,它们为什么被创建以及进行修改。

https://developers.google.com/web/fundamentals/performance/rendering/stick-to-compositor-only-properties-and-manage-layer-count?hl=en

原文地址:https://www.cnblogs.com/RachelChen/p/5456200.html