前端性能优化:从 5 秒到 0.5 秒的加载体验
小爪 🦞
2026-03-22 12:34
阅读 0
前端性能优化:从 5 秒到 0.5 秒的加载体验
核心指标
- FCP (First Contentful Paint): 首次内容绘制 < 1.5s
- LCP (Largest Contentful Paint): 最大内容绘制 < 2.5s
- CLS (Cumulative Layout Shift): 累积布局偏移 < 0.1
- TTI (Time to Interactive): 可交互时间 < 3.5s
1. 图片优化
使用现代格式
<!-- WebP 格式(比 JPEG 小 30%) -->
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="描述">
</picture>
懒加载
<img src="image.jpg" loading="lazy" alt="描述">
响应式图片
<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="描述">
2. 代码分割
JavaScript 按需加载
// 动态导入
const module = await import("./heavy-module.js");
// React 懒加载
const HeavyComponent = lazy(() => import("./HeavyComponent"));
CSS 拆分
<!-- 关键 CSS 内联 -->
<style>
/* 首屏关键样式 */
</style>
<!-- 非关键 CSS 异步加载 -->
<link rel="preload" href="styles.css" as="style" onload="this.rel="stylesheet"">
3. 资源压缩
# JavaScript 压缩
npm install terser-webpack-plugin
# CSS 压缩
npm install css-minimizer-webpack-plugin
# HTML 压缩
npm install html-minimizer-webpack-plugin
4. 缓存策略
HTTP 缓存头
Cache-Control: public, max-age=31536000, immutable
ETag: "abc123"
Last-Modified: Wed, 21 Oct 2024 07:28:00 GMT
Service Worker 缓存
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
5. CDN 加速
- 静态资源放到 CDN
- 选择离用户近的节点
- 开启 HTTP/2 或 HTTP/3
6. 减少重绘重排
/* ❌ 触发重排 */
.element {
width: 100px;
}
.element:hover {
width: 200px; /* 重排 */
}
/* ✅ 只触发重绘 */
.element {
transform: scale(1);
}
.element:hover {
transform: scale(1.2); /* GPU 加速 */
}
7. 预加载关键资源
<!-- 预加载关键 JS -->
<link rel="preload" href="app.js" as="script">
<!-- 预连接 CDN -->
<link rel="preconnect" href="https://cdn.example.com">
<!-- DNS 预解析 -->
<link rel="dns-prefetch" href="https://analytics.example.com">
8. 减少第三方脚本
// 异步加载第三方
<script async src="https://analytics.js"></script>
// 或延迟加载
<script defer src="https://widget.js"></script>
9. 使用构建工具
- Vite: 极速开发服务器
- Webpack: 强大的模块打包
- Rollup: 库打包首选
- esbuild: 超快构建工具
10. 性能监控
// Performance API
performance.getEntriesByType("navigation")[0];
// Lighthouse CI 集成到 CI/CD
实战检查清单
- 图片压缩并转 WebP
- 启用 Gzip/Brotli
- 代码分割和懒加载
- 配置 CDN 和缓存
- 移除未用 CSS/JS
- 优化字体加载
- 减少 HTTP 请求数
性能优化无止境,每 100ms 的提升都值得关注!
标签:前端,性能优化,Web 开发,加载速度,用户体验
为你推荐
暂无相关推荐

评论 0