# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
1.2 资源压缩与CDN
- 使用Webpack的TerserPlugin压缩JS
- 配置image-webpack-loader压缩图片
- 静态资源使用CDN加速
2. 渲染性能优化
2.1 虚拟列表
// React实现虚拟列表
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const VirtualList = () => (
<List
height={500}
itemCount={1000}
itemSize={35}
width={300}
>
{Row}
</List>
);
2.2 避免强制同步布局
// 错误示例:强制同步布局
function resizeAllParagraphs() {
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.width = box.offsetWidth + 'px';
}
}
// 正确示例:批量读取后批量写入
function resizeAllParagraphs() {
const width = box.offsetWidth;
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.width = width + 'px';
}
}
3. 内存管理
3.1 事件监听清理
// React组件卸载时清理事件
useEffect(() => {
const handleResize = () => {/*...*/};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
3.2 避免内存泄漏
// 定时器清理示例
useEffect(() => {
const timer = setInterval(() => {
// do something
}, 1000);
return () => clearInterval(timer);
}, []);
4. 网络请求优化
4.1 请求合并与缓存
// 使用SWR实现请求缓存
import useSWR from 'swr';
function Profile() {
const { data, error } = useSWR('/api/user', fetcher);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <div>hello {data.name}!</div>;
}
4.2 预加载关键资源
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="critical.js" as="script">
5. 监控与持续优化
5.1 性能指标监控
// 使用web-vitals库监控核心指标
import { getCLS, getFID, getLCP } from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
5.2 性能预算
// webpack性能预算配置
module.exports = {
performance: {
maxEntrypointSize: 512000,
maxAssetSize: 512000,
hints: 'warning'
}
};
最佳实践总结
-
关键渲染路径优化:
- 内联关键CSS
- 延迟非关键JS
- 优化首屏内容
-
资源优化:
- 使用WebP格式图片
- 实现响应式图片
- 字体子集化
-
代码优化:
- 避免深层嵌套
- 减少DOM操作
- 使用Web Worker处理耗时任务
-
缓存策略:
- 合理设置Cache-Control
- 使用Service Worker缓存
- 实现stale-while-revalidate策略
-
持续监控:
- 建立性能基准
- 设置性能告警
- 定期性能审计