# 前端性能优化实战指南
## 1. 资源加载优化
### 1.1 代码拆分与懒加载
```javascript
// 动态导入实现懒加载
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<Loading />}>
<LazyComponent />
</Suspense>
);
}
关键点:
- 使用Webpack的SplitChunksPlugin自动拆分代码
- 路由级懒加载减少首屏资源
- 预加载关键资源:
<link rel="preload">
1.2 资源压缩与CDN
# 开启Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript;
优化策略:
- 图片使用WebP格式,配合
<picture>降级方案 - 静态资源部署到CDN边缘节点
- 字体文件子集化(font-spider)
2. 渲染性能优化
2.1 减少重排重绘
// 批量DOM操作
const fragment = document.createDocumentFragment();
items.forEach(item => {
const li = document.createElement('li');
fragment.appendChild(li);
});
list.appendChild(fragment);
优化技巧:
- 使用CSS transform代替top/left动画
- 避免在循环中读取布局属性(offsetTop等)
- 使用will-change提示浏览器优化
2.2 虚拟列表优化
// React实现虚拟滚动
<VirtualList
itemCount={10000}
itemSize={35}
height={500}
>
{({ index, style }) => (
<div style={style}>Row {index}</div>
)}
</VirtualList>
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;
}
};
}
3.2 Web Worker应用
// 主线程
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = e => updateUI(e.data);
// worker.js
self.onmessage = function(e) {
const result = heavyCalculation(e.data);
self.postMessage(result);
};
4. 缓存策略
4.1 Service Worker缓存
// 缓存策略示例
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
缓存方案:
- 静态资源使用Cache-Control: max-age=31536000
- API响应使用ETag协商缓存
- IndexedDB存储非敏感数据
5. 监控与持续优化
5.1 性能指标采集
// 使用Performance API
const timing = performance.timing;
const loadTime = timing.loadEventEnd - timing.navigationStart;
关键指标:
- FCP (First Contentful Paint)
- LCP (Largest Contentful Paint)
- CLS (Cumulative Layout Shift)
5.2 性能测试工具
- Lighthouse自动化测试
- WebPageTest多地域测试
- Chrome DevTools性能面板
6. 现代化优化方案
6.1 渐进式Web应用
// manifest.json
{
"display": "standalone",
"prefer_related_applications": false
}
6.2 服务器端渲染优化
// Next.js混合渲染
export async function getServerSideProps(context) {
return { props: { data } };
}
总结
通过资源加载优化、渲染优化、代码优化、缓存策略和持续监控五个维度的综合施策,可以系统性地提升前端应用性能。建议建立性能预算(Performance Budget)并纳入CI流程,确保优化效果的持续性。现代浏览器提供的Performance API和各类调试工具是优化过程中的有力助手,应当充分加以利用。