Chrome 提出了 RAIL 性能衡量模型,以用户为中心的效果指标,RAIL 代表 Web 应用生命周期的四个不同方面:响应、动画、空闲和加载
![[Pasted image 20240811162033.png]]
性能指标主要可以分类两类:
<svg> 元素或非白色的 <canvas> 元素最简单的,一般前端应用都会关心以下几个指标:
视口内可见的最大图片或文本块的呈现时间(相对于用户首次导航到页面的时间)
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
console.log('LCP candidate:', entry.startTime, entry);
}
}).observe({type: 'largest-contentful-paint', buffered: true});
从用户首次与网页互动(即,点击链接、点按按钮或使用由 JavaScript 提供支持的自定义控件)到浏览器能够实际开始处理事件处理脚本以响应该互动的时间
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
const delay = entry.processingStart - entry.startTime;
console.log('FID candidate:', delay, entry);
}
}).observe({type: 'first-input', buffered: true});
许多网站都面临布局不稳定的问题:DOM 元素由于内容异步加载而发生移动
用来衡量在网页的整个生命周期内发生的每次意外布局偏移的最大突发布局偏移分数
addEventListener("load", () => {
let DCLS = 0;
new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
if (entry.hadRecentInput)
return; // Ignore shifts after recent input.
DCLS += entry.value;
});
}).observe({type: "layout-shift", buffered: true});
});
布局偏移分数是影响比例和距离比例的乘积:layout shift score = impact fraction * distance fraction
除了这些简单的指标外,要如何建立起对网页完整的性能指标呢?一套成熟又完善的解决方案为 Google 的 PageSpeed Insights (PSI)
PageSpeed Insights (PSI) 是一项免费的 Google 服务,可报告网页在移动设备和桌面设备上的用户体验,并提供关于如何改进网页的建议
Google 的另外一个服务 —— Lighthouse
| PageSpeed Insights | Lighthouse | |
|---|---|---|
| 如何访问 | https://pagespeed.web.dev/(浏览器访问;无需登录) | Google Chrome 浏览器扩展(推荐非开发人员使用) Chrome DevTools Node CLI 工具 Lighthouse CI |
| 数据来源 | Chrome 用户体验报告(真实数据) Lighthouse API(模拟实验室数据) |
Lighthouse API |
| 评估 | 一次一页 | 一次一页或一次多页 |
| 指标 | 核心网络生命、页面速度性能指标(首次内容绘制、速度指数、最大内容绘制、交互时间、总阻塞时间、累积布局偏移) | 性能(包括页面速度指标)、可访问性、最佳实践、SEO、渐进式 Web 应用程序(如果适用) |
| 建议 | 标有 Opportunities and Diagnostics 的部分提供了提高页面速度的具体建议 |
标有 Opportunities and Diagnostics 的部分提供了提高页面速度的具体建议。堆栈包可用于定制改进建议 |
web-vitals JavaScript 库使用 PerformanceObserver,用于测量真实用户的所有 Web Vitals 指标,其方式准确匹配 Chrome 的测量方式,提供了上述提到的各种指标数据:CLS、FID、LCP、INP、FCP、TTFB