目录
前端性能优化的 10 个黄金法则
作者:文文
为什么前端性能很重要?
根据研究,页面加载时间每延迟 100ms,转化率就会下降 1%。所以性能优化直接关系到用户体验和商业收益。
黄金法则 1:代码分割(Code Splitting)
使用 Webpack 或 Vite 的动态导入实现路由级别的代码分割:
// 不好的方式:一次性加载所有代码
import Dashboard from './pages/Dashboard'
// 好的方式:按需加载
const Dashboard = () => import('./pages/Dashboard')
效果:初始包体积减少 50-70%。
黄金法则 2:图片优化
使用现代格式
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img src="image.jpg" alt="description">
</picture>
图片压缩
# 使用 ImageOptim 或在线工具压缩
# PNG -> WebP 可以减少 25-35% 体积
黄金法则 3:懒加载(Lazy Loading)
// 原生 API
<img loading="lazy" src="image.jpg" alt="description">
// 或使用 Intersection Observer
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.src = entry.target.dataset.src
}
})
})
黄金法则 4:缓存策略
HTTP 缓存头
# 静态资源(永久缓存)
Cache-Control: public, max-age=31536000, immutable
# 动态内容(短期缓存)
Cache-Control: public, max-age=3600
# 不缓存
Cache-Control: no-cache, no-store, must-revalidate
Service Worker 缓存
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
)
})
黄金法则 5:减少重排和重绘
// 不好:每次都触发重排
for (let i = 0; i < 1000; i++) {
element.style.width = element.offsetWidth + 1 + 'px'
}
// 好:批量修改,只触发一次重排
let width = element.offsetWidth
for (let i = 0; i < 1000; i++) {
width += 1
}
element.style.width = width + 'px'
黄金法则 6:关键渲染路径优化
- 减少关键资源数
- 减少关键资源的大小
- 缩短关键路径长度
<!-- 优先级高的资源用 preload -->
<link rel="preload" href="critical.js" as="script">
<!-- 次要资源用 prefetch -->
<link rel="prefetch" href="next-page.js">
<!-- 异步加载非关键脚本 -->
<script defer src="analytics.js"></script>
黄金法则 7:CSS 优化
/* 避免过深的选择器 */
/* 不好 */
html body section .container .row .col-md-4 p { }
/* 好 */
.col-content { }
// 最小化 CSS
import MiniCssExtractPlugin from 'mini-css-extract-plugin'
黄金法则 8:JavaScript 优化
// 使用 Tree Shaking 移除未使用代码
export const used = () => {}
export const unused = () => {}
// 在 package.json 中标记副作用
{
"sideEffects": false
}
黄金法则 9:监控性能指标
// 使用 Web Vitals
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals'
getLCP(metric => console.log('LCP:', metric.value))
getFID(metric => console.log('FID:', metric.value))
getCLS(metric => console.log('CLS:', metric.value))
黄金法则 10:使用 CDN
- 地理位置就近分发内容
- 减少网络延迟
- 自动压缩和缓存
性能目标
| 指标 | 目标值 |
|---|---|
| FCP(首次内容绘制) | < 1.8s |
| LCP(最大内容绘制) | < 2.5s |
| CLS(累积布局偏移) | < 0.1 |
| TTFB(首字节时间) | < 600ms |
文文,2026 年 3 月 16 日
