前端性能优化 2024:Core Web Vitals 深度解析
Google 将 Core Web Vitals 作为排名因素后,性能优化成了每个前端开发者必须掌握的技能。本文深入讲解各项指标及优化方法。
Core Web Vitals 概述
Core Web Vitals 包括三个核心指标:
- LCP (Largest Contentful Paint) - 最大内容绘制
- CLS (Cumulative Layout Shift) - 累计布局偏移
- INP (Interaction to Next Paint) - 交互到下次绘制
LCP 优化(目标:< 2.5s)
1. 优化服务器响应时间
// 使用 CDN 加速静态资源
<script src="https://cdn.example.com/app.js"></script>
// Nginx 配置 gzip 压缩
gzip on;
gzip_types text/plain application/javascript application/json;
gzip_min_length 1000;2. 优化资源加载优先级
<!-- 预加载关键资源 -->
<link rel="preload" href="/hero-image.jpg" as="image" fetchpriority="high">
<!-- 预连接关键域名 -->
<link rel="preconnect" href="https://api.example.com">3. 使用现代图片格式
<picture>
<source srcset="/image.avif" type="image/avif">
<source srcset="/image.webp" type="image/webp">
<img src="/image.jpg" alt="描述" loading="lazy">
</picture>CLS 优化(目标:< 0.1)
1. 为图片和视频指定尺寸
<!-- 始终指定宽高 -->
<img src="p.jpg" width="800" height="600" alt="">
<!-- 视频使用 aspect-ratio -->
<div style="aspect-ratio: 16/9;">
<video src="video.mp4"></video>
</div>2. 避免动态插入内容
// 错误做法
document.body.insertAdjacentHTML("afterbegin", "<div>广告</div>");
// 正确做法:预留空间或使用固定高度
<div id="banner" style="min-height: 60px;"></div>3. 使用 font-display 策略
@font-face {
font-family: "MyFont";
src: url("/font.woff2") format("woff2");
font-display: swap;
}INP 优化(目标:< 200ms)
1. 分解长任务
// 将大任务分解为小块
function processLargeArray(items) {
const chunkSize = 100;
let index = 0;
function processChunk() {
const chunk = items.slice(index, index + chunkSize);
chunk.forEach(processItem);
index += chunkSize;
if (index < items.length) {
setTimeout(processChunk, 0);
}
}
processChunk();
}2. 使用 Web Worker
// worker.js
self.onmessage = (e) => {
const result = heavyComputation(e.data);
self.postMessage(result);
};
// main.js
const worker = new Worker("worker.js");
worker.postMessage(largeData);
worker.onmessage = (e) => console.log(e.result);3. 事件委托优化
// 使用事件委托而非多个事件监听
document.getElementById("list").addEventListener("click", (e) => {
if (e.target.matches(".item")) {
handleItemClick(e.target);
}
});性能监控工具
- Chrome DevTools:Performance 面板分析
- Lighthouse:自动化性能测试
- PageSpeed Insights:真实用户数据
- Web Vitals Chrome Extension:实时监控
实战 checklist
- 图片使用 WebP/AVIF 格式 + 懒加载
- 关键 CSS 内联,JS 异步加载
- 开启 gzip/brotli 压缩
- 使用 CDN 加速
- 预加载关键资源
- 避免布局抖动
- 分解长任务
总结
性能优化是一个持续的过程,建议建立自动化监控,及时发现和解决性能退化问题。