网站性能优化:从 LCP 到 CLS 的核心指标提升
Google Core Web Vitals 是搜索排名的重要因素,本文介绍如何优化三大核心指标。
三大核心指标
- LCP(最大内容绘制时间):目标 < 2.5s
- FID(首次输入延迟):目标 < 100ms
- CLS(累积布局偏移):目标 < 0.1
一、优化 LCP(最大内容绘制)
LCP 元素通常是首屏大图或标题文字。
图片优化
<!-- 1. 使用现代格式 -->
<picture>
<source srcset="hero.webp" type="image/webp">
<img src="hero.jpg" alt="" fetchpriority="high">
</picture>
<!-- 2. 设置宽高 -->
<img src="hero.jpg" width="1200" height="600" alt="">
<!-- 3. 预加载关键图片 -->
<link rel="preload" as="image" href="hero.webp">
字体优化
<!-- 预加载字体 -->
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
/* font-display: swap 避免文字闪烁 */
@font-face {
font-family: 'CustomFont';
src: url('font.woff2') format('woff2');
font-display: swap;
}
CSS 优化
<!-- 内联关键 CSS -->
<style>
.hero { display: flex; min-height: 60vh; }
</style>
<!-- 非关键 CSS 异步加载 -->
<link rel="preload" href="non-critical.css" as="style" onload="this.rel='stylesheet'">
二、优化 FID(首次输入延迟)
减少 JavaScript 阻塞
<!-- defer 异步加载 -->
<script src="app.js" defer></script>
<!-- 或 async -->
<script src="analytics.js" async></script>
拆分代码
// 只加载首屏需要的代码
const module = await import('./heavy-module.js');
使用 Web Worker
const worker = new Worker('compute.js');
worker.postMessage(data);
worker.onmessage = (e) => { console.log(e.data); };
三、优化 CLS(累积布局偏移)
图片设置宽高
<!-- 错误:没有宽高,加载后会推动内容 -->
<img src="image.jpg" alt="">
<!-- 正确 -->
<img src="image.jpg" width="800" height="600" alt="">
广告位预留空间
.ad-slot {
min-height: 250px; /* 预留高度 */
}
字体加载策略
@font-face {
font-family: 'CustomFont';
src: url('font.woff2') format('woff2');
font-display: swap; /* 先用回退字体,加载后切换 */
}
body {
font-family: 'CustomFont', system-ui, sans-serif;
}
四、测量工具
Google PageSpeed Insights
访问 pagespeed.web.dev,输入网址即可测试。
Chrome DevTools
按 F12 → Lighthouse 面板 → 生成报告。
Web Vitals 扩展
安装 Chrome 扩展「Core Web Vitals」,实时查看指标。
五、优化清单
- 图片使用 webp 格式
- 图片设置 width/height
- 关键 CSS 内联
- JS 使用 defer/async
- 字体使用 font-display: swap
- 启用 gzip/brotli 压缩
- 设置静态资源缓存头
- 使用 CDN 加速
- 移除未使用的 CSS/JS
- 延迟加载非首屏图片(loading=lazy)