# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
关键点:
- 使用Webpack的SplitChunksPlugin进行代码分割
- 路由级懒加载(React.lazy + Suspense)
- 图片懒加载(intersectionObserver API)
1.2 资源预加载
<!-- 关键资源预加载 -->
<link rel="preload" href="critical.css" as="style">
<link rel="prefetch" href="next-page.js" as="script">
优化策略:
- 关键CSS内联到HTML
- 非关键CSS异步加载
- 字体文件使用preconnect+preload
2. 渲染性能优化
2.1 虚拟列表优化长列表
// 使用react-window实现虚拟列表
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const Example = () => (
<List height={600} itemCount={1000} itemSize={35} width={300}>
{Row}
</List>
);
2.2 避免布局抖动
// 使用FastDOM避免强制同步布局
fastdom.measure(() => {
const width = element.clientWidth;
fastdom.mutate(() => {
element.style.width = width + 'px';
});
});
关键技巧:
- 使用will-change属性提示浏览器
- 减少重排重绘操作
- 动画使用transform/opacity
3. 缓存策略
3.1 Service Worker缓存
// 注册Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('SW registered');
});
}
缓存策略:
- Cache API实现离线缓存
- Workbox简化SW开发
- 版本化缓存更新机制
3.2 HTTP缓存头设置
# Nginx配置示例
location /static/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
最佳实践:
- 静态资源长期缓存
- 内容哈希实现缓存失效
- API响应合理设置缓存
4. 代码级优化
4.1 防抖节流
// 防抖实现
function debounce(func, delay) {
let timer;
return function() {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, arguments), delay);
};
}
4.2 Web Worker优化计算
// 主线程
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = (e) => { /* 处理结果 */ };
// worker.js
self.onmessage = (e) => {
const result = heavyCalculation(e.data);
self.postMessage(result);
};
优化技巧:
- 避免内存泄漏
- 减少DOM操作
- 使用WebAssembly处理密集计算
5. 监控与持续优化
5.1 性能指标监控
// 使用Performance API
const timing = performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;
// 使用web-vitals库
import { getCLS, getFID, getLCP } from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
5.2 Lighthouse自动化
// package.json脚本
{
"scripts": {
"audit": "lighthouse http://localhost:3000 --output=html"
}
}
持续优化:
- 建立性能预算
- CI集成性能测试
- A/B测试优化方案
总结
前端性能优化是系统工程,需要:
- 测量 → 2. 分析 → 3. 优化 → 4. 监控的闭环 从网络、渲染、内存多维度入手 结合具体业务场景选择优化策略