# 前端性能优化实战指南
## 1. 资源加载优化
**图片优化:**
- 使用WebP格式替代JPEG/PNG(兼容性允许情况下)
- 实现懒加载:`<img loading="lazy">`
- 响应式图片:`<picture>` + `srcset`
```html
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" loading="lazy">
</picture>
代码分割:
- Webpack动态导入:
const module = await import('./module.js');
- React.lazy + Suspense:
const LazyComponent = React.lazy(() => import('./Component'));
<Suspense fallback={<Spinner/>}>
<LazyComponent/>
</Suspense>
2. 渲染性能优化
CSS优化策略:
- 避免深层嵌套选择器(保持<3层)
- 使用will-change属性预声明动画元素:
.animated {
will-change: transform, opacity;
}
- 优先使用transform/opacity触发GPU加速
JavaScript执行优化:
- 防抖/节流高频事件:
const throttledFn = _.throttle(fn, 100);
window.addEventListener('resize', throttledFn);
- 使用Web Worker处理CPU密集型任务
- 避免强制同步布局:
// 错误示例(触发布局抖动)
for(let i=0; i<elements.length; i++) {
elements[i].style.width = box.offsetWidth + 'px';
}
3. 缓存策略
Service Worker缓存:
// sw.js
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open('v1').then((cache) => {
return cache.addAll(['/app.js','/style.css']);
})
);
});
HTTP缓存头设置:
Cache-Control: public, max-age=31536000
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
4. 代码级优化
React优化技巧:
- 使用React.memo避免不必要的重渲染
const MemoComponent = React.memo(({data}) => {
return <div>{data}</div>;
});
- 精细化useEffect依赖数组
useEffect(() => {
// 仅当id变化时执行
}, [id]);
Vue优化方案:
- v-once用于静态内容
<div v-once>{{ staticContent }}</div>
- 使用计算属性缓存结果
computed: {
filteredList() {
return this.list.filter(item => item.active);
}
}
5. 监控与持续优化
性能指标采集:
// 使用Performance API
const [entry] = performance.getEntriesByName('first-contentful-paint');
console.log('FCP:', entry.startTime);
// 监听长任务
const observer = new PerformanceObserver((list) => {
for(const entry of list.getEntries()) {
console.log('Long task:', entry.duration);
}
});
observer.observe({entryTypes: ['longtask']});
优化工作流:
- 使用Lighthouse进行自动化测试
- 建立性能预算(如bundle < 200KB)
- CI集成性能检测:
# .github/workflows/audit.yml
- name: Run Lighthouse
uses: foo-software/lighthouse-check-action@v2
with:
urls: 'https://example.com'
budgetPath: './budget.json'
关键工具推荐
- Chrome DevTools Performance面板
- Webpack Bundle Analyzer
- Speed Measure Plugin
- React Profiler
- Vue DevTools Performance标签
通过组合应用这些技术,可使页面加载速度提升40%+,交互响应时间减少30%+。建议从Lighthouse评分最低的项开始优化,采用渐进式优化策略。