Web 性能直接影响用户体验和商业指标。Google 的 Core Web
Vitals(CWV)已成为搜索排名因素之一,也是衡量 Web
性能的标准指标体系。本文将深入解析 LCP、FID(已被 INP 取代)、CLS
三大核心指标的优化策略,覆盖图片优化、代码分割、懒加载、资源提示、Service
Worker 缓存以及性能监控体系的搭建。
Core Web Vitals 指标详解
graph LR
A[Core Web Vitals] --> B[LCP<br/>Largest Contentful Paint<br/>最大内容绘制]
A --> C[INP<br/>Interaction to Next Paint<br/>交互到下次绘制]
A --> D[CLS<br/>Cumulative Layout Shift<br/>累计布局偏移]
B --> B1["Good: ≤2.5s<br/>Needs Improvement: ≤4s<br/>Poor: >4s"]
C --> C1["Good: ≤200ms<br/>Needs Improvement: ≤500ms<br/>Poor: >500ms"]
D --> D1["Good: ≤0.1<br/>Needs Improvement: ≤0.25<br/>Poor: >0.25"]
style B fill:#0cce6b,color:#000
style C fill:#ffa400,color:#000
style D fill:#ff4e42,color:#fff
// BAD: Long task blocks main thread button.addEventListener('click', () => { // 200ms synchronous computation const result = heavyComputation(data); updateDOM(result); });
// GOOD: Break into smaller tasks with scheduler button.addEventListener('click', async () => { // Yield to main thread between tasks const chunk1 = processChunk(data.slice(0, 1000)); await scheduler.yield(); // or use setTimeout(0) as fallback
@keyframes slideIn { to { transform: translateY(0); } }
1 2 3 4 5 6 7 8
// 5. Handle web font loading to avoid FOUT/FOIT // Use font-display: swap with size-adjust const fontFace = newFontFace('CustomFont', 'url(/fonts/custom.woff2)', { display: 'swap', });
document.fonts.add(fontFace); fontFace.load();
图片优化
flowchart TD
A[图片优化策略] --> B[格式选择]
A --> C[响应式图片]
A --> D[懒加载]
A --> E[CDN + 缓存]
B --> B1[WebP: 通用最佳]
B --> B2[AVIF: 更高压缩率]
B --> B3[SVG: 图标/插图]
C --> C1[srcset + sizes]
C --> C2["<picture> element"]
D --> D1[loading='lazy']
D --> D2[Intersection Observer]
style A fill:#3498db,color:#fff
style B1 fill:#2ecc71,color:#fff
style B2 fill:#9b59b6,color:#fff
graph TD
A[请求类型] --> B{静态资源?<br/>图片/字体}
A --> C{CSS/JS?}
A --> D{API 请求?}
B -->|是| E[Cache First<br/>优先缓存]
C -->|是| F[Stale While Revalidate<br/>先返回缓存再更新]
D -->|是| G[Network First<br/>优先网络]
E --> H[缓存命中 → 直接返回]
E --> I[缓存未命中 → 网络请求 → 缓存]
F --> J[返回缓存 + 后台更新]
G --> K[网络请求 → 成功则返回并缓存]
G --> L[网络失败 → 返回缓存兜底]
style E fill:#2ecc71,color:#fff
style F fill:#f39c12,color:#000
style G fill:#3498db,color:#fff