前端性能优化:从指标到实践
Core Web Vitals 已经成为搜索引擎排名的重要因素,性能优化不再只是锦上添花,而是关乎产品存亡。本文系统梳理三大核心指标的优化策略。
LCP(最大内容绘制)优化:
// Next.js 图片优化
import Image from "next/image";
<Image
src="/hero.jpg"
alt="首页横幅"
width={1200}
height={600}
priority // 预加载,提升 LCP
placeholder="blur"
/>
// 字体优化 - 避免布局偏移
import { Inter } from "next/font/google";
const inter = Inter({
subsets: ["latin"],
display: "swap", // 字体交换策略
});
CLS(累积布局偏移)优化:
/* 为动态内容预留空间 */
.ad-slot {
min-height: 250px;
}
/* 图片/视频指定宽高比 */
.responsive-img {
aspect-ratio: 16 / 9;
width: 100%;
height: auto;
}
/* 避免动态注入内容 */
/* 错误:在现有内容上方插入元素 */
/* 正确:使用固定位置或预留空间 */
INP(交互到下一次绘制)优化需要减少主线程阻塞:
// 长任务拆分
function processLargeArray(items) {
const chunkSize = 50;
let index = 0;
function processChunk() {
const end = Math.min(index + chunkSize, items.length);
for (let i = index; i < end; i++) {
processItem(items[i]);
}
index = end;
if (index < items.length) {
requestIdleCallback(processChunk);
}
}
processChunk();
}
在我们的电商项目中,通过以上优化,LCP 从 4.2s 降到 1.8s,CLS 从 0.35 降到 0.05,INP 从 350ms 降到 120ms。搜索排名提升了 15 位,转化率提高了 12%。