# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
1.2 资源压缩
module.exports = {
plugins: [
new TerserPlugin(),
new CssMinimizerPlugin(),
new ImageMinimizerPlugin()
]
}
1.3 CDN加速
<script src="https://cdn.example.com/react@18.2.0/umd/react.production.min.js"></script>
2. 渲染性能优化
2.1 虚拟列表
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;
requestAnimationFrame(() => {
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].style.width = width + 'px';
}
});
}
3. 缓存策略
3.1 Service Worker缓存
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('v1').then((cache) => {
return cache.addAll([
'/',
'/index.html',
'/styles/main.css',
'/scripts/main.js'
]);
})
);
});
3.2 HTTP缓存头
Cache-Control: public, max-age=31536000
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
4. 代码优化
4.1 防抖与节流
function debounce(func, wait) {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, arguments), wait);
};
}
function throttle(func, limit) {
let inThrottle;
return function() {
if (!inThrottle) {
func.apply(this, arguments);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
4.2 Web Worker
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = (e) => {
console.log('Received:', e.data);
};
self.onmessage = (e) => {
const result = heavyComputation(e.data);
self.postMessage(result);
};
5. 监控与分析
5.1 性能指标
const timing = window.performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;
performance.getEntriesByType('paint').forEach((entry) => {
console.log(`${entry.name}: ${entry.startTime}`);
});
5.2 错误监控
window.addEventListener('error', (event) => {
const { message, filename, lineno, colno, error } = event;
logError({ message, filename, lineno, colno, stack: error.stack });
});
window.addEventListener('unhandledrejection', (event) => {
logError({ reason: event.reason });
});