前端性能优化实战指南
性能优化是前端开发的核心竞争力,直接影响用户体验和业务转化。本文将带你深入理解现代前端性能优化的完整体系。
🎯 核心性能指标
1. Core Web Vitals
Google定义的三个核心指标:
- LCP (Largest Contentful Paint): 最大内容绘制时间 < 2.5s
- FID (First Input Delay): 首次输入延迟 < 100ms
- CLS (Cumulative Layout Shift): 累积布局偏移 < 0.1
2. Lighthouse评分体系
- Performance (性能)
- Accessibility (无障碍)
- Best Practices (最佳实践)
- SEO (搜索引擎优化)
- PWA (渐进式Web应用)
⚡ 优化策略详解
资源加载优化
// 1. 代码分割
const LazyComponent = React.lazy(() => import('./LazyComponent'));
// 2. 预加载关键资源
<link rel="preload" href="critical.css" as="style">
<link rel="prefetch" href="next-page.js" as="script">
// 3. 图片优化
<img src="image.webp" loading="lazy" width="800" height="400" alt="描述">
构建优化技巧
- Tree Shaking: 消除未使用的代码
- 代码压缩: Terser、CSS压缩
- 缓存策略: 长期缓存、运行时缓存
📊 性能监控
// 真实用户监控(RUM)
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log('LCP:', entry.startTime);
}
}).observe({entryTypes: ['largest-contentful-paint']});
🛠️ 工具链推荐
- Lighthouse: 自动化性能审计
- WebPageTest: 多地点性能测试
- Bundle Analyzer: 包体积分析
- Chrome DevTools: 性能面板
总结
性能优化是一个持续的过程,需要建立监控、分析、优化的完整闭环。