DEV Community

WDSEGA
WDSEGA

Posted on

前端性能优化实战:从FCP到LCP,让你的网站快3倍

你的网站加载需要多久?根据Google的研究,页面加载时间每增加1秒,转化率就下降7%。在2026年,Core Web Vitals已经成为Google搜索排名的直接因素。

Core Web Vitals核心指标

指标 含义 目标值
LCP 最大内容元素的渲染时间 < 2.5秒
INP 用户交互到页面响应的时间 < 200ms
CLS 页面视觉稳定性 < 0.1

图片优化:最容易见效的优化

图片通常占页面总大小的50%以上。

<picture>
  <source srcset="hero.avif" type="image/avif">
  <source srcset="hero.webp" type="image/webp">
  <img src="hero.jpg" alt="Hero" loading="lazy" width="800" height="450">
</picture>
Enter fullscreen mode Exit fullscreen mode

AVIF比JPEG小30-50%,WebP比JPEG小25-35%。

JavaScript优化:减少主线程阻塞

代码分割和懒加载

import { lazy, Suspense } from "react";
const Dashboard = lazy(() => import("./pages/Dashboard"));

function App() {
  return (
    <Suspense fallback={<LoadingSpinner />}>
      <Routes>
        <Route path="/dashboard" element={<Dashboard />} />
      </Routes>
    </Suspense>
  );
}
Enter fullscreen mode Exit fullscreen mode

Intersection Observer懒加载

function useLazyLoad(threshold = 0.1) {
  const ref = useRef(null);
  const [isVisible, setIsVisible] = useState(false);
  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          observer.unobserve(entry.target);
        }
      },
      { threshold }
    );
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, [threshold]);
  return [ref, isVisible];
}
Enter fullscreen mode Exit fullscreen mode

CSS优化:减少渲染阻塞

.card {
  contain: layout style paint;
  content-visibility: auto;
  contain-intrinsic-size: 0 500px;
}
Enter fullscreen mode Exit fullscreen mode

content-visibility: auto 可以让长列表的初始渲染时间减少50%以上。

HTTP缓存策略

location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2|avif|webp)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}
Enter fullscreen mode Exit fullscreen mode

优化效果对比

指标 优化前 优化后 提升
LCP 4.2s 1.3s 69%
INP 350ms 85ms 76%
CLS 0.25 0.02 92%

核心原则:先测量再优化、优先优化LCP、减少主线程阻塞、保持视觉稳定、建立监控体系。


📢 本文为精简版,完整版包含独家工具推荐和深度分析,请访问 WD Tech Blog 查看!

关注我的博客获取最新科技资讯、AI教程和效率工具推荐!

Top comments (0)