Web性能优化实战经验

性能优化是Web开发中的重要话题。一个快速响应的网站不仅能提供更好的用户体验,还能提高SEO排名和转化率。

性能指标

Core Web Vitals

Google提出的三个核心指标:

  1. LCP (Largest Contentful Paint):最大内容绘制时间
  2. FID (First Input Delay):首次输入延迟
  3. CLS (Cumulative Layout Shift):累积布局偏移

优化策略

1. 资源加载优化

<!-- 预加载关键资源 -->
<link rel="preload" href="/critical.css" as="style">
<link rel="preload" href="/hero-image.jpg" as="image">

<!-- 预连接第三方域名 -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="dns-prefetch" href="https://api.example.com">

2. 图片优化

<!-- 响应式图片 -->
<picture>
  <source media="(min-width: 800px)" srcset="large.webp" type="image/webp">
  <source media="(min-width: 800px)" srcset="large.jpg">
  <source srcset="small.webp" type="image/webp">
  <img src="small.jpg" alt="描述" loading="lazy">
</picture>

3. 代码分割

// 路由级别的代码分割
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));

// 组件级别的代码分割
const HeavyComponent = lazy(() => import('./HeavyComponent'));

4. 缓存策略

// Service Worker缓存
self.addEventListener('fetch', event => {
  if (event.request.destination === 'image') {
    event.respondWith(
      caches.open('images').then(cache => {
        return cache.match(event.request).then(response => {
          return response || fetch(event.request).then(fetchResponse => {
            cache.put(event.request, fetchResponse.clone());
            return fetchResponse;
          });
        });
      })
    );
  }
});

性能监控

1. 使用Performance API

// 监控页面加载时间
window.addEventListener('load', () => {
  const perfData = performance.getEntriesByType('navigation')[0];
  console.log('页面加载时间:', perfData.loadEventEnd - perfData.fetchStart);
});

// 监控资源加载
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    console.log('资源加载时间:', entry.name, entry.duration);
  });
});
observer.observe({ entryTypes: ['resource'] });

2. 核心指标监控

// 监控LCP
new PerformanceObserver((entryList) => {
  for (const entry of entryList.getEntries()) {
    console.log('LCP:', entry.startTime);
  }
}).observe({ entryTypes: ['largest-contentful-paint'] });

// 监控CLS
let clsValue = 0;
new PerformanceObserver((entryList) => {
  for (const entry of entryList.getEntries()) {
    if (!entry.hadRecentInput) {
      clsValue += entry.value;
    }
  }
  console.log('CLS:', clsValue);
}).observe({ entryTypes: ['layout-shift'] });

优化工具

  1. Lighthouse:Google的性能审计工具
  2. WebPageTest:详细的性能分析
  3. Chrome DevTools:实时性能监控
  4. Bundle Analyzer:分析打包文件大小

实践建议

  1. 建立性能预算:为关键指标设定目标值
  2. 持续监控:在CI/CD中集成性能检查
  3. 渐进式优化:优先优化影响最大的问题
  4. 用户体验优先:平衡性能和功能需求

总结

Web性能优化是一个系统性工程,需要从多个维度进行考虑和实施。通过合理的优化策略和持续的监控,我们可以为用户提供更好的Web体验。

记住:测量 → 分析 → 优化 → 验证,这是性能优化的基本循环。