【译】了解累积布局偏移

529 阅读27分钟

安妮·沙利文 (Annie Sullivan)史蒂夫·科比斯 (Steve Kobes)#PerfMatters 上发表的演讲:《了解累积布局偏移》(2020)

Intro

Hi everybody, I'm Annie, I'm the tech lead of Chrome speed metrics team. We designed the performance metrics in Chrome and we want to standardize them so they can be available in other browsers and tools too.
大家好,我是 Annie,Chrome 速度指标团队的技术主管。我们在 Chrome 中设计了性能指标并且希望将它们标准化,以便它们也可以在其他浏览器和工具中使用。

Today I'm really excited to talk to you about a new metric we've been working on: Cumulative Layout Shift. It's our first metric that focuses on user experience beyond performance. We're going to do a deep dive on how and why we developed the metric. I hope you can measure and improve it.
非常高兴今天能和大家分享一个我们一直在研究的新指标:累积布局偏移(CLS)。这是我们提出的首个关注用户体验而不是性能的指标。我们将深入探讨我们为什么以及如何开发该指标。希望大家能够衡量并改进它。

I'm also happy to be joined by Steve Kobes, the engineer who lead design and development on Cumulative Layout Shift. He'll be able to give you all the details about the design process and the choices we made along the way.
我也很高兴 Steve Kobes 能够参与这次分享,他是领导累积布局偏移设计和开发的工程师。他将为大家讲解有关设计过程的所有细节以及我们在此过程中做出的选择。

Let's start with a problem.
首先我们来看一个问题。

动画1.gif

It's a really frustrating part of the web today, you're trying to read a page and suddenly the content moves around and you can't find your place. Or worse, you're trying to click on something and then the content moves and now you click on the wrong thing.
这是现如今网络上一个非常令人沮丧的现状,你正试图阅读一个页面,突然网页内容四处移动然后你就找不到你先前阅读的位置了。甚至更糟糕的是,你试图点击什么东西,这时网页内容发生了移动,然后你就会点到一个错误的元素上。

And it isn't just a problem during the page load, it could happen well up to the site is loaded.
这不仅仅是页面加载过程中会出现的问题,它也可能会在网站加载之后发生。

I know it's really most frustrating to me when I'm reading an article and scrolled off way through and then the content shifts around, and now I have no idea where I was.
对我来说,当我滚动浏览一篇文章然后内容动来动去的时候真的很令人沮丧,这个时候我完全不知道我在阅读哪一部分了。

But if you're developing a site, it can be really hard to know you have a problem. Maybe it looked fine originally and an upgrade made things shifts around, maybe it only shifts on certain viewports on slow network connections.
但如果你是一个网页开发者,你可能很难在开发过程中发现这个问题。也许它最初看起来没什么问题,某些升级使内容发生了偏移,也许它只在慢速网络的某些视口上才会发生偏移。

We want to help developers address these problems by providing a metric that measures how bad the layout shift on the pages and making it available in both lab tools and in real user monitoring.
我们希望通过提供一个衡量页面布局偏移程度的指标并使其在实验室工具和真实用户监控中可用来帮助开发人员解决这些问题。

So we spend a lot of time working on it, we looked at thousands of sites and we tried a lot of approaches. I'm gonna hand it over to Steve to talk about what we came up with.
因此,我们花了很多时间研究这个问题,我们调研了数以千计的网站,尝试了很多方法。现在有请 Steve 来介绍一下我们的工作成果。

Title

Hello I'm Steve, and I'm going to tell you a little more about the design of the CLS formula and how the browser measures layout instability.
大家好,我是 Steve,下面由我来为大家介绍一下更多关于 CLS 公式的设计以及浏览器如何衡量布局不稳定性的内容。

Impact Region

To quantify layout instability, we looked first at how much of the visual area on the screen was affected by it, we call this The Impact Region.
要量化布局不稳定性,我们首先要看屏幕上有多少可视区域受到了它的影响,我们称之为影响区域(The Impact Region)。

So here's an example of a page. Where the content jumps because ad was inserted. We first identify all the dom elements that shifted from one animation frame to the next.
这是一个示例页面。网页内容因为插入广告而发生了跳动。首先我们来确认一下所有从一个动画帧到下一个动画帧的过程中发生了移动的 DOM 元素有哪些。

动画.gif

So let's see the jump again, and in this case we identify the big white block of text as a shifted element. Now of course the reason this element shifted was that an ad was inserted, but the ad itself is not a shifted element, because it didn't exist in the previous frame. We don't want to penalize inserting new elements because that's a very common thing that happens during progressive rendering as chunks of the page are loaded from the network.
我们再看一下这个跳动,在这种情况下,我们将大的白色文本块识别为偏移元素(shifted element)。当然,这个元素偏移的原因是插入了广告,但是广告本身不是偏移元素,因为它在前一帧中不存在。我们不想把新插入的元素标记为偏移元素,这是因为在渐进式渲染期间,由于页面中的块是从网络异步加载的,插入元素是非常常见的事情。

Snipaste_2022-12-18_16-10-20.jpg

So we're really focused on elements that already existed but are now in a different visual location. Once we have that set of shifted elements, we take the union of the before and after state of the visual area of each shifted element.
我们真正关注的是已经存在但视觉位置发生变化的元素。一旦我们有了一组偏移元素,我们就得到每个偏移元素的视觉区域的前后状态的并集。

So here's what it looked like before the shift.
这是元素偏移之前的样子。

image.png

And here's the previous visual area and the new visual area.
这是之前的视觉区域和之后的视觉区域。

image.png

image2.png

So we combine those for all the shifted elements and that gives us the impact region.
我们将所有偏移元素的视觉区域组合起来就得到了影响区域(Impact Region)。

image.png

And you can see in this case the ad is actually inside the impact region, which might seem appropriate, but the ad is not directly contributing to the impact region, the reason it starts that far up is that we're including the previous visual area of the white box with the text.
如你所见,在这个例子中,广告元素实际上位于影响区域内,这看起来没什么问题,但广告并不直接影响影响区域(Impact Region),这里的影响区域之所以从那个上面开始计算,是因为我们将上一帧的文本盒子的视觉区域一起包含在内。

In this case, the impact region is a rectangle, but it doesn't have to be if there are many shifted elements in the same animation frame or if an element shifts both horizontally and vertically, then the impact region can be a more complicated shape or even a union of disjoint shapes.
在这个例子中,影响区域是一个矩形,但如果在同一个动画帧中有许多偏移的元素,或者一个元素同时发生了水平和垂直方向的移动,那么影响区域可能就会是更复杂的形状,甚至是一些互不相交的形状。

But in any case, we look at the size of the impact region as compared to the viewport and this gives us some normalization across different device sizes, window sizes and resolutions.
但在任何情况下,我们都会将影响区域的大小与视口进行比较,这为我们提供了针对不同设备大小、窗口大小和分辨率的一些规范。

image.png

We really want to look not at the absolute numerical area, but at a ratio and the ratio of the impact region to the viewport gives us a fraction which we call The Impact Fraction.
我们真正关注的并不是区域面积的绝对值,而是看一个比率,影响区域与视口的比率,我们称之为影响分数(Impact Fraction)。

image.png

So our first prototype of CLS looked only at the impact region, but we noticed this didn't do a good job of capturing how far things moved. If something moves a lot it's more distracting, but if it only moves by a few pixels, it's not as bad, even if the area of the thing that moved is large.
我们的第一个 CLS 原型只关注影响区域,但我们注意到这并不能很好地反映内容移动的距离。某个内容移动距离越大,它就会越分散注意力,但如果它只移动了几个像素,即使移动的内容占据了很大的面积,也不会有太大的问题。

So we decided to ask what's the farthest distance that any shifted element moved by? In this case, the shifted element moved from here to here.
因此我们决定看一下任意产生位移的元素它移动的最大距离是多少?在这个例子中,移动的元素从这里移动到了这里。

image.png

image.png

So that's our maximum move distance for this frame.
那这就是这一帧的当中元素移动的最大距离。

image.png

We compare that to the viewport and get another fraction: The Distance Fraction.
我们将其与视口进行比较,并得到另一个距离分数(Distance Fraction)。

image.png

I should also note in this example, we only have vertical movement on a tall device, but move distance is access agnostic, so the top of the fraction is really maximum movement distance in either the horizontal or the vertical direction, and the bottom of the fraction is really the viewport width or height whichever is larger.
需要指出的是,在这个例子中,使用的终端是一个“高”的设备,元素只在垂直方向发生了位移,但是移动距离与访问无关,因此,距离分数的分子实际上是水平或垂直方向上的最大移动距离,而分母实际上是视口的宽度或高度,以较大者为准。

So now we have two fractions that we want to incorporate into an overall score: The Impact Fraction and The Distance Fraction. When we multiply them together we get the layout shift score for a single animation frame or a single moment in time in the browsing session.
那么现在我们有两个分数:影响分数(Impact Fraction)和距离分数(Distance Fraction),我们希望把它们合并为一个总分。当我们把它们相乘,就能得到单个动画帧或浏览会话中单个时刻的布局偏移分数(Layout Shift Score)。

image.png

And if we add them up from the start of the page load till the user leaves the page, and we get a cumulative layout shift score or CLS score.
如果我们把从页面加载开始到用户离开页面的所有布局偏移分数相加,就会得到一个累积布局偏移分数(Cumulative Layout Shift Score)或者简称为 CLS 分数(CLS Score)。

image.png

Interaction

Another problem we ran into was that websites are interactive and we didn't want to give a bad score just because the rendering changed in response to user input like clicking a button to expand something.
我们遇到的另一个问题是由于网站是交互式的,我们不想仅仅因为渲染会响应用户输入(例如单击按钮展开某些内容)而发生变化就给出不好的分数。

动画1.gif

So a naive solution here might have been for CLS to ignore layout shifts that happen inside event handlers, but layout shifts in response to input don't necessarily happen synchronously inside the event handler, the shift might happen after a network request or inside a task in a custom scheduler. And in general it's really hard for the browser to trace a layout shift back to an input through these kinds of asynchronous steps to really understand that the shift is because of the input.
这里我们可能会想当然地认为让 CLS 忽略事件处理程序内部发生的布局偏移能够解决这个问题,但响应输入的布局偏移不一定在事件处理程序内部同步发生,这种偏移可能发生在网络请求之后或自定义调度程序的 task 中。通常浏览器很难通过这些异步步骤将布局偏移回溯到输入动作,从而真正理解布局偏移是由输入引起的。

So our solution is to not even try to do that but instead to basically give you a window of time after a click or a tap or a key press, when you're allowed to change layout without bumping the CLS score and we call that The Input Exclusion Window, because we're excluding the layout shifts that happened within that window of time.
因此,我们采用的解决方案是根本不去做这样的尝试,基本上我们会在单击鼠标、轻击屏幕或按下键盘后给您一个时间窗口,在这个时间窗口内,您可以在不影响 CLS 分数的情况下更改布局,我们称之为:输入排除窗口(Input Exclusion Window),因为我们排除了在该时间窗口内发生的布局偏移。

image.png

Animations

Another challenge we faced was with animations, and we saw that a lot of sites with high CLS scores had animations like auto advancing image carousels. CSS lets you animate any property you like but if you animate a layout related property like the position offsets left right, left top, right and bottom, then we're rerunning the browsers layout engine on every animation frame, and every frame produces a layout shift, now it might be a small layout shift that is the impact region and the maximum movement distance are both pretty small for each frame but the cumulative score will grow unbounded, so your total CLS will be large and proportional to how long the user spends on the page, which is not very good.
我们面临的另一个挑战是动画(Animations),我们注意到很多 CLS 评分高的网站都有像轮播图这样的动画。CSS 允许你为任意的属性设置动画,但如果你设置与布局相关的属性的动画(如 left、right、top、bottom 等),那么我们将在每个动画帧上重新运行浏览器布局引擎,每一帧都会产生布局偏移,它可能是一个很小的布局偏移量,即影响区域(Impact Region)和最大移动距离(Maximum Movement Distance)对于每一帧都很小,但累积分数将无限增长,因此你的 CLS 总分数会变得很大,并且与用户在页面上停留的时长成正比,这样的结果是我们不太能够接受的。

动画12.gif

The solution that we adopted was to ignore changes to the transform property, so as long as your carousel is implemented with transform animations, it won't blow up your CLS score. And in some ways you could say this is a bit of a hack, but we think this is really in keeping with the principles of punishing layout instability because transform doesn't influence the surrounding layout,so if you shift an element by transforming it, none of the elements below it will move around, but if you shift it with a position offset then they can. Transform also means browsers can easily parallelizing by running the animation on a separate thread from the thread that runs the JavaScript, this means the page will be more efficient and responsive even if it's script heavy.
我们采用的解决方案是忽略 transform 属性的更改,因此只要你的轮播是使用 transform 动画实现的,它就不会影响你的 CLS 分数。你可能会说这有点 hack,但我们认为这确实符合处置布局不稳定性的原则,因为 transform 不会影响周围的布局。如果你通过 transform 来移动一个元素,它下面的元素都不会四处移动,但是如果你通过 position 属性来移动它,情况就完全不一样了。 Transform 还意味着浏览器可以并行地处理 JavaScript 线程和动画线程,这意味着即使脚本很重,页面也会更高效、更灵敏。

Conclusion

So that's an overview of the CLS formula and some of the trade-offs that went into it. We know CLS doesn't correlate perfectly to the user's perceptual experience of layout instability, but it tries to capture an approximation of it in a way that's easy for the developer to reason about, it doesn't give the full story of the users experience but we think that full story can be approached by CLS in conjunction with other metrics like Largest Contentful Paint and First Input Delay.
以上就是 CLS 公式的概述以及其中的一些权衡。我们知道 CLS 与用户对布局不稳定性的感知体验并不完全相关,但它试图以一种易于开发人员推理的方式获取近似值,它并没有给出用户体验的完整故事线,但我们认为 CLS 可以结合其它指标(例如 LCP 和 FID)来了解完整情况。

Finally, I'll note that the definition of CLS will probably change over time, as we incorporate feedback and look at how it's used on the web and how we can make it a more useful signal. All right, I'll turn it back to Annie now to tell you more about how to improve CLS on your sites. Thanks everyone.
最后需要指出的是,CLS 的定义可能会随着时间的推移而改变,因为我们会收集反馈并不断探索它在 web 中的使用方式以及如何使其成为更有用的指标。好了,我现在把画面转回给 Annie,她将跟大家分享更多关于如何改进你网站 CLS 分数的信息。谢谢大家。

Measuring Layout Shift

Thanks Steve. So now that we know what Cumulative Layout Shift is, let's talk about how to measure and improve it. First, how do you see your site's cumulative layout shift? We've made it available by a few different methods in the lab and in real user monitoring. Let's start with a lab. First, cumulative layout shift is available in lighthouse six which is currently in beta you can see this score right in the metric summary at the top, here's a screenshot. We're also going to add additional debugging info and audits to lighthouse over time.
谢谢 Steve。现在我们了解了什么是 CLS,接下来我们来看如何衡量和改进它。首先,如何查看你网站的 CLS 分数?我们在实验室工具和真实用户监控中通过几种不同的方法使其可用。我们从实验室工具开始。首先,CLS 在目前处于测试阶段的 lighthouse 中可用,如下面这个屏幕截图所示,你可以在顶部的指标摘要中看到这个分数。随着时间的推移,我们还会向 lighthouse 添加额外的调试信息。

image.png

Cumulative Layout Shift is also available in webpagetest, it's going to show up in the timing section for each run really soon. But maybe you're stuck at home and you don't have anything to do and you really want to see your score in webpagetest right now, it's already available in the raw JSON as chromeUserTiming.CumulativeLayoutShift, here's a screenshot of a webpagetest run. You can get to it by clicking view JSON result from the main summary tab. If you want automated tests using webpagetest you can parse this JSON from the cumulative layout shift as well.
CLS 也可以在 webpagetest 中使用,它很快就会显示在每次运行的计时部分。但也许你正被困在家里,无事可做,你现在就很想在 webpagetest 中看到你的分数,那么你也可以在原始 JSON 中通过 chromeUserTiming.CumulativeLayoutShift 找到它,这是 webpagetest 运行的屏幕截图,你可以通过单击主摘要选项卡中的 view JSON result 来访问。如果你想使用 webpagetest 进行自动化测试,你也可以从累积布局转换中解析这个 JSON 对象。

注:这是 2020 年的分享,现在 webpagetest 已经完全支持 CLS 指标。

image.png

But what about real user monitoring? The easiest way to get started is to use a chrome user experience report, cumulative layout shift is in the table as layout_instability.cumulative_layout_shift. Here's an example query, that outputs a histogram of scores for a site.
那真实的用户监控呢?最简单的入门方法是使用 chrome 用户体验报告(CrUX),累积布局偏移在表中为 layout_instability.cumulative_layout_shift 字段。下面是一个查询示例,它输出站点分数的直方图。

image.png

But what if you want a more fine-grained detail for your site, cumulative layout shift is exposed via a JavaScript API in chromium browsers. Let's walk through some example code.
如果你想知道更细颗粒度的细节,可以通过 Chrome 浏览器中的 JavaScript API 来获取。让我们来看一下示例代码。

// Catch errors since some browsers throw when using the new `type`
// option. https://bugs.webkit.org/show_bug.cgi?id=209216
try {
  // Store the current layout shift score for the page.
  let cumulativeLayoutShiftScore = 0;

  // Detect new layout shift occurrences and updates the
  // `cumulativeLayoutShiftScore` variable.
  const observer = new PerformanceObserver((list) => {
    for (const entry of list.getEntries()) {
      // Only count layout shifts without recent user input.
      if (!entry.hadRecentInput) {
        cumulativeLayoutShiftScore += entry.value;
      }
    }
  });
 
  observer.observe({ type: 'layout-shift', buffered: true });
 
  // Send the final score to your analytics back end once
  // the page's lifecycle state becomes hidden.
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') {
      //Force any pending records to be dispatched.
      observer.takeRecords();
      observer.disconnect();
      //Log the final score to the console.
      console.log('CLS:', cumulativeLayoutShiftScore);
    }
  })
} catch (e) {
  //Do nothing if the browser doesn't support this API.
}

First, we want to create a variable to store the sum of the layout shifts.
首先,我们创建一个变量来存储累积布局偏移量。

Next, we'll create a performance observer, the observer is notified of layout shifts, notice the buffered argument, the observed method at the bottom there, we can start observing after the page is loaded, and get buffered entries that have already occurred, no need to block loading with the script to start observing.
接下来,我们创建一个性能监测对象(PerformanceObserver),Observer 会订阅布局变化的通知,注意这里的参数和下面的 observe 方法,页面加载后,在浏览器的性能时间轴记录新的 performance entry 的时候将会被通知,并且不会阻碍 script 脚本的加载。

We'll track entries with type layout-shift, and since some shifting is expected after a user input, we'll ignore entries that had recent input, the rest will add to our cumulative score.
我们将监测类型为 layout-shift 的条目,并且由于在用户输入后预计会发生一些偏移,我们将忽略最近输入的条目,其余条目将添加到累积分数中。

Finally, when the page is hidden, we'll force any pending records to be dispatched and report them.
最后,当页面被隐藏时,我们将强制发送并报告所有 pending 状态的记录。

This code mirrors the way we report cumulative layout shift in the chrome user experience report. Through the API is pretty flexible, you can imagine tweaking it. Maybe you want to measure cumulative layout shift before the page loads and after the page loads separately, you could have two different scores and reset the variable. Same thing if you had a single page app, you could track the score for each route separately. In fact, the API doesn't even require that the layout shift score is cumulative, we're just adding it here but you can imagine doing something different, like for example, calculating a rate, maybe you want to know the layout shifts per minute.
这段代码反映了我们在 Chrome 用户体验报告(CrUX)中报告累积布局变化的方式。APl 是相当灵活的,你可以根据你的需求调整调用方式。也许你想分别测量页面加载前和页面加载后的累积布局偏移量,你可以创建两个不同的分数并重置变量。同样地,如果你有一个单页面应用,你可以分别跟踪每个路由的分数。事实上,APl 甚至不要求布局偏移分数是累积的,我们只是在这个例子中做了累加,但你完全可以做一些不同的事情,比如,如果你想知道每分钟的布局偏移量,你可以去计算出一个比率结果。

So that's a summary of how to measure cumulative layout shift in the lab and the really using monitoring.
以上就是关于如何在实验室工具以及真实用户监控中测量累积布局偏移量的总结。

What's a good Score?

But now that we know how to measure it, what's a good score? Ideally, pages wouldn't have any layout shift at all, but that might not be reachable for all sites. So our team thought a lot about what a good score for layout shift might be, we dug through sets of pages that consistently scored in different buckets, and we came to agreement that if you sum up all the impact fractions multiplied by all the distance fractions, 0.1 is a pretty good score, we recommend trying to stay below it.
现在我们知道如何去衡量累积布局偏移了,那么一个比较好的分数是多少呢?理想情况下,页面根本不会有任何布局变化,但可能并非所有站点都可以实现。因此,我们的团队考虑了很多关于布局偏移的好分数,我们仔细研究了在不同桶中一致得分的页面集,最终一致认为,如果将所有影响分数乘以所有距离分数相加,0.1 是一个比较好的分数,我们建议你的 CLS 分数应当尽量保持在 0.1 以下。

What if your score is high?

So what if you measure your layout shift and is really high, what can you do? We're working on adding additional audits to lighthouse and debugging information to dev tools, but right now you can see layout shifts in dev tools. It's a little bit buried you need to use the more tools menu and open up the rendering panel, once you're in the rendering panel, select the layout shift regions checkbox, then as the layout shifts, the shifted content will be highlighted in blue, it's updated as you interact with the page so you can see layout shifts that happen after load.
那么如果你测量你的 CLS 分数,并且分数很高,你能做些什么呢?我们正在努力为 lighthouse 添加额外的审查指标,为开发工具添加调试信息,但现在你已经可以在开发工具中查看布局偏移信息了。它藏的有点深,你需要使用 More tools 菜单并打开 Rendering 面板,在 Rendering 面板中,选择 Layout Shift Regions 复选框,当发生布局偏移的时候,偏移的内容将以蓝色突出显示,它在你与页面交互时更新,以便你可以看到页面加载后发生的布局变化。

image.png

image.png

image.png

We found that as we dug into a lot of layout shifts over the past year, being able to see which content shifted the most, was the most helpful part of debugging, so we think this is a really useful feature in dev tools, and we're also working on adding the list of shifted elements to our JavaScript API.
在过去的一年里,我们深入研究了很多布局偏移,能够看到哪些内容变化最多,这是调试中最有帮助的部分,我们认为这将是开发工具中一个非常有用的功能,与此同时,我们还致力于将偏移元素列表添加到我们的 JavaScript API 中。

Common problems

So now let's get to common problems, we looked at a lot of layout shifty pages over the past year and we've even done analysis to understand what the biggest sources of layout shift were, we'd like to share some of our findings, and I thought that was addressing some really common problems.
现在我们来看一下几个常见的问题,我们在过去的一年里查看了很多布局偏移的页面,我们甚至进行了分析以了解布局偏移的最大来源是什么,这里分享一些我们的成果,我认为这些发现能够解决一些非常普遍的问题。

First, one of the very most common causes of layout shifts is unsized images, I've thrown out of this quick pages in example, you can see that the images are unsized so the text pops around a lot as it loads, I changed my example to just have width and height attributes for the images and now the layout shift is gone. If it's possible always add sizing attributes to your image and video elements, if not, looking the techniques to reserve the space with CSS like I've linked in the slides(CSS aspect ratio).
首先,布局偏移最常见的一个原因是未设定尺寸的 image 元素,在这个示例中,可以看到由于 image 未设置大小,因此文本元素的位置在图片加载后会弹出很多。我将示例稍微做了一点更改,仅仅是给图片加上了 width 和 height 属性,布局偏移就消失了。如果可行的话,始终为图像和视频元素指定大小属性,如果不能,尝试使用 CSS 预留空间技术,就像我在幻灯片中贴出的链接那样(CSS aspect ratio)。

动画11.gif

动画12.gif

Another really common cause of layout shift is fonts, especially on slow connections, text can display before the font is fully loaded, and then everything shifts around when the font loads and the text is updated. To address this, consider font-display: optional; the CSS shows the fallback font, if the font isn't loaded, without doing the swap, when the font does load, but it still makes the request so that the font catched for next time. If font-display: optional; isn't an option for you, then try to match the font metrics of the fallback font and web font as closely as possible, there are font style matching tools to help, I link one in the slides(font style matching tools).
布局偏移的另一个非常常见原因是字体,尤其是在网速较慢的情况下,文本内容可以在字体完全加载之前显示,然后当字体加载完成文本内容更新时,所有内容都将发生偏移。为了解决这个问题,可以考虑 font-display: optional; 属性,如果字体未加载,CSS 将显示备用字体,而不在字体加载完成时进行切换,但它仍然会发出请求,以便下次使用字体。如果 font-display: optional; 不是您的选择,您可以尝试尽可能接近地匹配后备字体和网络字体的字体规格,有字体样式匹配工具可以提供帮助,我在幻灯片中链接了一个(font style matching tools)。

动画21.gif

Another cause of layout shift is content that's injected after the main content is loaded, often it's these little promo bars at the top of the page that the user can close, if you can't reserve space for this type of bar, consider making it position: fixed; so they just overlays the content a little bit. But a worse cause of layout shift is larger injecting content, the best thing to do in this case is reserve space for the content ahead of time, so that shifts don't think so shifts around as it comes in.
布局偏移的另一个原因是在加载主要内容后注入的内容,通常是页面顶部的这些用户可以手动关闭的小促销栏,如果您不能为此类元素预留空间,请考虑为其指定 position: fixed; 属性,这样它们只会稍微覆盖一点点内容。但是布局偏移的一个更糟糕的原因是更大的注入内容,在这种情况下最好的办法是提前为它预留空间,这样偏移就不会在额外内容注入时四处移动。

动画21.gif

Another really common cause of layout shift is just flash of unstyled content, this example is a really common case we see, this sites using a normal bootstrap menu but it loads the CSS really late, so you see the full HTML the menu laid out before it's properly styled and hidden. I recommend that when you're looking at the order to load resources in, always consider really carefully what styles are needed to display the initial content correctly.
布局偏移的另一个常见的原因是无样式内容的闪现,这是我们看到的非常常见的案例,这个网站使用很常见的引导菜单,但它加载 CSS 的时间很晚,所以你可以看到菜单在正确样式化并隐藏之前的完整 HTML 结构。我建议您在设置加载资源的顺序时,务必仔细考虑正确显示初始内容需要哪些样式。

动画22.gif

The last really common anti-pattern we see, is animations that trigger layout changes. These animations run on the main thread and when devices are slow it can cause a lot of jerk, it's much better to prefer transform animations to animations of properties that trigger layout changes.
我们看到的最后一个常见的场景是触发布局更改的动画。这些动画在主线程上运行,当设备运行缓慢时,它会引起大量的抖动,相比触发布局更改的属性动画,transform 动画就要好得多(csstriggers)。

动画223.gif

Outro

Thanks so much for listening, I really hope it's been helpful to learn about how do we develop the metric for layout shift and how you can measure and improve your own site. Our team continues to work on new metrics and improvements to existing metrics, as well as web performance api's. As we look back on the development of cumulative layout shift, one thing we really like to improve upon is working more with the community. We're taking a break from Twitter right now but we'd still really love to hear from you, if you're interested in our work or if you want to contribute or give feedback on performance metrics and apis, please reach out at speed metrics devs at chromium.org. Thanks so much.
非常感谢您的聆听,希望本次分享对您了解我们如何制定布局偏移的指标,以及您如何衡量和改进自己的网站有所帮助。我们的团队将继续致力于新指标的制定和对现有指标的改进,web 性能 api 亦是如此。当我们回顾累积布局偏移的发展时,我们真正希望改进的事是与社区更多地合作。我们现在正在暂停 Twitter,但我们仍然非常希望听到您的消息,如果您对我们的工作感兴趣,或者如果您想对性能指标和 api 做出贡献或提供反馈,请联系 chromium.org 上的 speed metrics 开发人员。非常感谢。