# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
- 使用Webpack的SplitChunksPlugin进行代码分割
- 路由级懒加载减少首屏资源体积
- 图片懒加载使用IntersectionObserver API
1.2 资源压缩与缓存
# Nginx配置示例
gzip on;
gzip_types text/plain text/css application/json application/javascript;
- 启用Gzip/Brotli压缩
- 设置长期缓存策略(Cache-Control: max-age=31536000)
- 使用WebP等现代图片格式
2. 渲染性能优化
2.1 减少重绘回流
const fragment = document.createDocumentFragment();
items.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
fragment.appendChild(li);
});
list.appendChild(fragment);
- 使用transform代替top/left动画
- 避免频繁读取会触发回流的属性(如offsetWidth)
- 使用will-change属性提示浏览器优化
2.2 虚拟列表优化
import { FixedSizeList as List } from 'react-window';
<List
height={400}
itemCount={1000}
itemSize={50}
width={300}
>
{({ index, style }) => (
<div style={style}>Row {index}</div>
)}
</List>
- 只渲染可视区域内的元素
- 适用于大数据量表格/列表场景
- 支持动态高度项目
3. JavaScript优化
3.1 防抖与节流
function throttle(fn, delay) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
fn.apply(this, args);
lastCall = now;
}
};
}
- 高频事件处理优化(resize/scroll)
- 输入框搜索建议使用防抖
- 动画帧使用requestAnimationFrame
3.2 Web Workers
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = e => console.log(e.data);
self.onmessage = function(e) {
const result = heavyCalculation(e.data);
self.postMessage(result);
};
- 将CPU密集型任务移出主线程
- 保持UI响应流畅
- 适用于图像处理、大数据计算等场景
4. 监控与持续优化
4.1 性能指标采集
const timing = performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;
import {getCLS, getFID, getLCP} from 'web-vitals';
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
- 关键指标:FP/FCP/LCP/TTI/TBT
- 真实用户监控(RUM)
- 使用Lighthouse进行自动化测试
4.2 渐进式优化策略
- 首屏关键资源内联
- 非关键CSS异步加载
- 预加载重要资源
<link rel="preload" href="critical.css" as="style">
<link rel="prefetch" href="next-page.js" as="script">
5. 现代API应用
5.1 Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => console.log('SW registered'))
.catch(err => console.log('SW registration failed'));
}
5.2 IntersectionObserver
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src;
observer.unobserve(entry.target);