# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
1.2 资源压缩与CDN
- 使用Webpack的TerserPlugin压缩JS
- 配置Gzip/Brotli压缩
- 静态资源使用CDN加速
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 避免强制同步布局
// 错误示例 - 导致布局抖动
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 事件监听清理
// 组件卸载时移除事件监听
useEffect(() => {
const handleResize = () => {
// 处理逻辑
};
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);
3.2 避免内存泄漏
- 及时清除定时器
- 避免循环引用
- 使用WeakMap替代Map存储DOM引用
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="preconnect" href="https://fonts.gstatic.com">
5. 监控与持续优化
5.1 性能指标监控
// 使用web-vitals库监控核心指标
import { getCLS, getFID, getLCP } from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
5.2 Lighthouse持续集成
# GitHub Actions配置示例
name: Lighthouse CI
on: [push]
jobs:
lhci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install && npm run build
- uses: actions/setup-node@v1
- run: npm install -g @lhci/cli
- run: lhci autorun
最佳实践总结
-
关键渲染路径优化:
- 内联关键CSS
- 异步加载非关键JS
- 预加载关键资源
-
代码层面优化:
- 避免深层嵌套组件
- 合理使用useMemo/useCallback
- 减少不必要的重新渲染
-
构建工具优化:
- 配置Tree Shaking
- 使用持久化缓存
- 按需polyfill
-
运行时优化:
- 使用Web Worker处理耗时任务
- 合理使用requestIdleCallback
- 优化动画性能(使用transform/opacity)
-
渐进式增强:
- 骨架