LCP 优化:从 5 秒降到 2.5 秒以内 —— 一次技术深度剖析

实现 2.5 秒以内的 LCP 需要对整个渲染管线进行系统性优化。本技术指南将逐步讲解如何运用经过验证的策略,把 LCP 从 5 秒以上降低到 2.5 秒以内。

LCP 剖析:什么会被渲染为 LCP

LCP 元素通常是:

第 1 步:确定你的 LCP 元素

使用 Chrome DevTools 来确定 LCP 元素:

  1. 打开 Performance 面板
  2. 勾选 "Web Vitals" 复选框
  3. 录制一次页面加载
  4. 找到绿色的 LCP 标记
  5. 点击查看元素详情

第 2 步:优化关键路径

服务端优化

目标 TTFB < 800ms:

# Enable compression
gzip on;
gzip_types text/css application/javascript image/svg+xml;

# Cache static assets
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
  expires 1y;
  add_header Cache-Control "public, immutable";
}

# HTTP/2 Server Push for critical resources
http2_push /css/critical.css;
http2_push /js/critical.js;

资源提示(Resource Hints)

<!-- Preconnect to origins -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://cdn.example.com">

<!-- Preload LCP image -->
<link rel="preload" as="image" href="/hero.webp" fetchpriority="high">

<!-- DNS prefetch for non-critical -->
<link rel="dns-prefetch" href="https://analytics.example.com">

第 3 步:图片优化管线

格式选择

格式 适用场景 相比 JPEG 的节省
AVIF 现代浏览器中的照片 50-70%
WebP 支持范围广泛的照片 25-35%
JPEG XL 下一代照片格式 30-50%
SVG 图标与插画 矢量优势

响应式图片实现

<picture>
  <source
    type="image/avif"
    srcset="/hero-400.avif 400w, /hero-800.avif 800w, /hero-1200.avif 1200w"
  />
  <source
    type="image/webp"
    srcset="/hero-400.webp 400w, /hero-800.webp 800w, /hero-1200.webp 1200w"
  />
  <img
    src="/hero-1200.jpg"
    srcset="/hero-400.jpg 400w, /hero-800.jpg 800w, /hero-1200.jpg 1200w"
    width="1200"
    height="630"
    alt="Hero image"
    fetchpriority="high"
    decoding="async"
  />
</picture>

第 4 步:CSS 优化

关键 CSS 内联

提取并内联首屏以上的 CSS:

<head>
  <style>
    /* Critical CSS - inlined */
    .hero { width: 100%; height: 60vh; }
    .hero-image { object-fit: cover; width: 100%; }
    .nav { position: fixed; top: 0; z-index: 100; }
  </style>
  <link rel="stylesheet" href="/css/main.css" media="print" onload="this.media='all