如何提高前端应用的性能
1. 代码优化
1.1 减少DOM操作
DOM操作非常消耗性能,应尽量减少:
// 不好的做法
for(let i=0; i<100; i++) {
document.getElementById('list').innerHTML += `<li>Item ${i}</li>`;
}
// 好的做法 - 使用文档片段
const fragment = document.createDocumentFragment();
for(let i=0; i<100; i++) {
const li = document.createElement('li');
li.textContent = `Item ${i}`;
fragment.appendChild(li);
}
document.getElementById('list').appendChild(fragment);
1.2 事件委托
减少事件监听器数量:
// 不好的做法
document.querySelectorAll('button').forEach(btn => {
btn.addEventListener('click', handleClick);
});
// 好的做法 - 事件委托
document.getElementById('container').addEventListener('click', (e) => {
if(e.target.tagName === 'BUTTON') {
handleClick(e);
}
});
1.3 避免强制同步布局
读写DOM属性会导致浏览器强制重新计算布局:
// 不好的做法 - 强制同步布局
const width = element.offsetWidth;
element.style.width = width + 10 + 'px';
// 好的做法 - 使用requestAnimationFrame
requestAnimationFrame(() => {
const width = element.offsetWidth;
element.style.width = width + 10 + 'px';
});
2. 资源优化
2.1 图片优化
- 使用WebP格式替代JPEG/PNG
- 使用响应式图片(
srcset) - 懒加载非首屏图片
<img src="placeholder.jpg" data-src="image.jpg" loading="lazy">
2.2 代码分割
现代打包工具支持按需加载:
// 动态导入
const module = await import('./module.js');
// React懒加载
const LazyComponent = React.lazy(() => import('./Component'));
2.3 缓存策略
合理设置HTTP缓存头:
Cache-Control: public, max-age=31536000
3. 渲染优化
3.1 使用虚拟列表
对于长列表渲染:
import { FixedSizeList as List } from 'react-window';
<List
height={500}
itemCount={1000}
itemSize={35}
width={300}
>
{({ index, style }) => (
<div style={style}>Row {index}</div>
)}
</List>
3.2 CSS优化
- 避免使用
@import - 减少重绘和回流
- 使用
will-change提示浏览器优化
.animate {
will-change: transform;
}
3.3 Web Workers
将耗时任务放到Worker线程:
// main.js
const worker = new Worker('worker.js');
worker.postMessage(data);
worker.onmessage = (e) => {
console.log(e.data);
};
// worker.js
self.onmessage = (e) => {
const result = heavyCalculation(e.data);
self.postMessage(result);
};
4. 网络优化
4.1 HTTP/2
启用HTTP/2多路复用,减少连接数。
4.2 预加载关键资源
<link rel="preload" href="critical.css" as="style">
<link rel="preconnect" href="https://api.example.com">
4.3 服务端渲染(SSR)
首屏使用服务端渲染,提升首屏速度。
5. 监控与分析
5.1 性能指标
关注核心Web指标:
- LCP (最大内容绘制)
- FID (首次输入延迟)
- CLS (累积布局偏移)
5.2 性能分析工具
- Chrome DevTools Performance面板
- Lighthouse
- WebPageTest
6. 最佳实践总结
- 测量优先:使用工具量化性能问题
- 渐进增强:确保基础功能在低端设备可用
- 按需加载:只加载当前需要的资源
- 缓存利用:最大化利用浏览器缓存
- 持续优化:性能优化是持续过程
通过以上方法系统性地优化前端应用,可以显著提升用户体验和业务指标。