# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<Loading />}>
<LazyComponent />
</Suspense>
);
}
1.2 资源压缩与CDN
- 使用Webpack的TerserPlugin压缩JS
- 配置Gzip/Brotli压缩
- 静态资源部署到CDN
1.3 预加载关键资源
<link rel="preload" href="critical.css" as="style">
<link rel="prefetch" href="next-page.js" as="script">
2. 渲染性能优化
2.1 虚拟列表实现
import { FixedSizeList as List } from 'react-window';
<List
height={500}
itemCount={1000}
itemSize={50}
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';
}
}
2.3 使用CSS硬件加速
.transform-element {
transform: translateZ(0);
will-change: transform;
}
3. 状态管理优化
3.1 精细化状态更新
const MemoComponent = React.memo(function MyComponent(props) {
});
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
3.2 状态管理库选择
- 轻量级场景:Context + useReducer
- 复杂场景:Redux Toolkit/Zustand
- 异步场景:RTK Query/SWR
4. 网络请求优化
4.1 请求合并与缓存
import useSWR from 'swr';
function Profile() {
const { data, error } = useSWR('/api/user', fetcher);
}
4.2 请求优先级控制
fetch('/api/data', { priority: 'high' });
5. 监控与持续优化
5.1 性能指标监控
import { getCLS, getFID, getLCP } from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
5.2 性能预算
module.exports = {
performance: {
maxEntrypointSize: 512000,
maxAssetSize: 512000,
hints: 'warning'
}
};
6. 移动端专项优化
6.1 首屏加速方案
6.2 手势优化
element.addEventListener('touchstart', onTouchStart, { passive: true });
7. 构建优化
7.1 Tree Shaking配置
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
}
};
7.2 持久化缓存
module.exports = {
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
}
};
8. 图片优化
8.1 现代图片格式