# 前端性能优化实战指南
## 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
- 配置image-webpack-loader压缩图片
- 静态资源部署到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';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const App = () => (
<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 避免内存泄漏
useEffect(() => {
const timer = setInterval(() => {
}, 1000);
return () => clearInterval(timer);
}, []);
4. 缓存策略
4.1 Service Worker缓存
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js');
});
}
4.2 HTTP缓存头设置
# Nginx配置示例
location /static/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
5. 性能监控
5.1 核心Web指标
import {getCLS, getFID, getLCP} from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
5.2 自定义性能埋点
const measurePerf = () => {
const timing = window.performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;
console.log(`页面加载耗时: ${loadTime}ms`);
};
window.addEventListener('load', measurePerf);
6. 构建优化
6.1 Tree Shaking配置
module.exports = {
optimization: {
usedExports: true,
minimize: true,
}
};
6.2 持久化缓存
module.exports = {
cache: {
type: 'filesystem',
buildDependencies: {
config: [__filename]
}
}
};
7. 移动端优化
7.1 300ms点击延迟解决
<meta name="viewport" content="width=device-width, initial-scale=1.0">
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick