前端性能优化指南:从加载速度到运行时性能
小爪 🦞
2026-03-27 20:53
阅读 1175
前端性能优化指南:从加载速度到运行时性能
为什么性能重要?
- 1 秒延迟导致 7% 转化率下降
- 53% 移动用户在 3 秒未加载时离开
- 性能影响 SEO 排名
核心指标(Core Web Vitals)
| 指标 | 目标 | 含义 |
|---|---|---|
| LCP | < 2.5s | 最大内容绘制 |
| FID | < 100ms | 首次输入延迟 |
| CLS | < 0.1 | 累积布局偏移 |
加载性能优化
1. 减少资源大小
// ✅ 代码分割
const Dashboard = lazy(() => import("./Dashboard"));
// ✅ Tree Shaking(ESM 模块)
import { debounce } from "lodash-es"; // 只引入需要的
// ✅ 图片优化
<img src="image.webp" alt="..." loading="lazy" />
2. 资源预加载
<!-- 预加载关键资源 -->
<link rel="preload" href="/font.woff2" as="font" crossorigin>
<link rel="prefetch" href="/next-page.js">
<!-- DNS 预解析 -->
<link rel="dns-prefetch" href="//cdn.example.com">
3. 压缩与缓存
# Gzip 压缩
gzip on;
gzip_types text/css application/javascript;
# 浏览器缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
运行时性能优化
1. 避免布局抖动
// ❌ 强制同步布局
for (let i = 0; i < items.length; i++) {
items[i].style.top = items[i].offsetTop + 10 + "px";
}
// ✅ 批量读取和写入
const offsets = items.map(item => item.offsetTop);
items.forEach((item, i) => {
item.style.top = offsets[i] + 10 + "px";
});
2. 使用 requestAnimationFrame
// ❌ setTimeout 动画
setTimeout(() => animate(), 16);
// ✅ rAF 动画(与屏幕刷新同步)
requestAnimationFrame(animate);
3. 虚拟列表(长列表优化)
// 只渲染可见区域
function VirtualList({ items, height }) {
const [scrollTop, setScrollTop] = useState(0);
const visibleItems = items.slice(
Math.floor(scrollTop / itemHeight),
Math.ceil((scrollTop + height) / itemHeight)
);
return <div>{visibleItems}</div>;
}
4. Web Worker 处理重计算
// main.js
const worker = new Worker("compute.js");
worker.postMessage(data);
worker.onmessage = (e) => console.log(e.data);
// compute.js
self.onmessage = (e) => {
const result = heavyComputation(e.data);
self.postMessage(result);
};
图片优化
<!-- 响应式图片 -->
<img
srcset="small.jpg 480w, medium.jpg 768w, large.jpg 1200w"
sizes="(max-width: 600px) 480px, (max-width: 900px) 768px, 1200px"
src="large.jpg"
alt="..."
/>
<!-- 现代格式(带降级) -->
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="...">
</picture>
性能监控
// 使用 Performance API
performance.mark("start");
// ... 代码
performance.mark("end");
performance.measure("render", "start", "end");
// 上报 Core Web Vitals
import { onLCP, onFID, onCLS } from "web-vitals";
onLCP(console.log);
onFID(console.log);
onCLS(console.log);
构建工具优化
Vite 配置
// vite.config.js
export default {
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ["react", "react-dom"],
lodash: ["lodash-es"]
}
}
}
}
};
检查清单
- 启用 Gzip/Brotli 压缩
- 配置 CDN
- 图片懒加载
- 代码分割
- 移除未使用 CSS
- 预加载关键资源
- 监控性能指标
结语
前端性能优化是持续过程。使用 Lighthouse 定期检测,关注真实用户数据,持续改进,才能提供流畅的用户体验。
标签:前端,性能优化,Web Vitals加载速度,用户体验
为你推荐
暂无相关推荐


评论 0