如何提高前端应用的性能
1. 代码优化
1.1 减少代码体积
// 使用Tree Shaking移除未使用代码
import { specificFunction } from 'large-library';
// 代码分割
const LazyComponent = React.lazy(() => import('./LazyComponent'));
1.2 优化JavaScript执行
// 使用requestAnimationFrame优化动画
function animate() {
// 动画逻辑
requestAnimationFrame(animate);
}
// 避免强制同步布局
// 错误示例
element.style.width = '100px';
const width = element.offsetWidth; // 强制同步布局
// 正确示例
const width = element.offsetWidth;
element.style.width = '100px';
2. 资源加载优化
2.1 图片优化
<!-- 使用WebP格式 -->
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="示例图片">
</picture>
<!-- 懒加载 -->
<img src="placeholder.jpg" data-src="real-image.jpg" loading="lazy">
2.2 资源预加载
<!-- 关键资源预加载 -->
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="main.js" as="script">
<!-- DNS预解析 -->
<link rel="dns-prefetch" href="//cdn.example.com">
3. 渲染优化
3.1 减少重绘和回流
/* 使用transform代替top/left */
.box {
transform: translate(100px, 100px);
}
/* 使用will-change提示浏览器 */
.animated {
will-change: transform;
}
3.2 虚拟列表优化长列表
// React中使用react-window
import { FixedSizeList } from 'react-window';
<List
height={500}
width={300}
itemSize={50}
itemCount={1000}
>
{Row}
</List>
4. 缓存策略
4.1 合理配置HTTP缓存
Cache-Control: max-age=31536000, immutable
ETag: "123456"
4.2 Service Worker缓存
// 注册Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js');
}
5. 性能监控
5.1 使用Performance API
// 测量代码执行时间
performance.mark('start');
// 执行代码
performance.mark('end');
performance.measure('measure', 'start', 'end');
5.2 核心Web指标监控
// 监控LCP
new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
const lastEntry = entries[entries.length - 1];
console.log('LCP:', lastEntry.renderTime || lastEntry.loadTime);
}).observe({type: 'largest-contentful-paint', buffered: true});
6. 最佳实践总结
-
关键渲染路径优化:
- 内联关键CSS
- 延迟非关键JS
- 优化首屏内容
-
资源优化:
- 压缩图片和字体
- 使用现代格式(WebP, AVIF)
- 按需加载资源
-
框架优化:
- 使用代码分割
- 实现组件懒加载
- 避免不必要的重新渲染
-
网络优化:
- 启用HTTP/2
- 使用CDN
- 配置合理的缓存策略
-
持续监控:
- 建立性能预算
- 定期进行性能审计
- 监控真实用户性能数据