# 前端性能优化实战指南
## 1. 资源加载优化
**图片优化:**
- 使用WebP格式替代JPEG/PNG,平均可减少30%体积
- 实现懒加载:`<img loading="lazy" src="image.jpg">`
- 响应式图片:`<picture><source media="(min-width: 800px)" srcset="large.jpg">`
**代码拆分:**
```javascript
// 动态导入组件
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
<Suspense fallback={<Loader/>}>
<HeavyComponent/>
</Suspense>
预加载关键资源:
<link rel="preload" href="critical.css" as="style">
<link rel="preconnect" href="https://api.example.com">
2. 渲染性能优化
CSS优化策略:
/* 避免强制同步布局 */
.animate {
will-change: transform; /* 提前告知浏览器 */
transform: translateZ(0); /* 触发GPU加速 */
}
JavaScript执行优化:
// 使用requestAnimationFrame处理动画
function animate() {
element.style.transform = `translateX(${pos}px)`;
pos++;
if (pos < 100) requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
虚拟滚动实现:
// React示例
<VirtualList
itemCount={10000}
itemSize={50}
height={500}
>
{({index, style}) => (
<div style={style}>Item {index}</div>
)}
</VirtualList>
3. 缓存策略
Service Worker缓存:
// 注册Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(reg => console.log('SW registered'))
.catch(err => console.log('SW error', err));
}
HTTP缓存头设置:
Cache-Control: public, max-age=31536000, immutable
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
4. 代码级优化
Tree Shaking配置:
// webpack.config.js
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
}
};
Webpack分包策略:
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
}
}
}
}
5. 监控与持续优化
性能指标采集:
// 使用Performance API
const [pageNav] = performance.getEntriesByType('navigation');
console.log('TTFB:', pageNav.responseStart - pageNav.requestStart);
Lighthouse自动化:
# 安装Lighthouse CI
npm install -g @lhci/cli
lhci autorun --collect.url=https://example.com
6. 现代化技术方案
Web Workers应用:
// 主线程
const worker = new Worker('worker.js');
worker.postMessage(data);
// worker.js
self.onmessage = (e) => {
const result = heavyComputation(e.data);
self.postMessage(result);
};
WASM集成示例:
WebAssembly.instantiateStreaming(fetch('module.wasm'))
.then(obj => {
const result = obj.instance.exports.compute();
});
最佳实践总结
- 测量优先:使用Chrome DevTools的Performance面板分析瓶颈
- 渐进增强:优先保证核心功能快速加载
- 持续监控:建立性能预算并设置CI检查
- 按需优化:根据用户实际访问路径优化关键渲染路径
# 快速检查工具
webpack-bundle-analyzer --port 8888 stats.json
通过组合应用这些技术,可将页面加载时间降低40-60%,交互响应速度提升50%以上。建议从Lighthouse评分低于80分的项目开始逐步优化,每次聚焦解决1-2个关键问题。