# 前端性能优化实战指南
## 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()
]
}
1.3 缓存策略
# Nginx配置示例
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires 1y;
add_header Cache-Control "public";
}
2. 渲染性能优化
2.1 虚拟列表
import { FixedSizeList as List } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const Example = () => (
<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. JavaScript优化
3.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);
}
};
}
3.2 Web Worker
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = function(e) {
console.log('Result:', e.data);
};
self.onmessage = function(e) {
const result = heavyComputation(e.data);
self.postMessage(result);
};
4. 网络优化
4.1 HTTP/2
# Nginx启用HTTP/2
server {
listen 443 ssl http2;
server_name example.com;
# SSL配置...
}
4.2 预加载关键资源
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="app.js" as="script">
5. 监控与分析
5.1 性能指标API
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(entry.name + ": " + entry.startTime);
}
});
observer.observe({type: 'paint', buffered: true});
new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
const lastEntry = entries[entries.length - 1];
console.log('LCP:', lastEntry.startTime);
}).observe({type: 'largest-contentful-paint', buffered: true});
5.2 内存分析
function getMemoryUsage() {
const used = process.memoryUsage().heapUsed / 1024 / 1024;
console.log(`Memory used: ${Math.round(used * 100) / 100} MB`);
}
6. 移动端优化
6.1 触摸事件优化