前端性能优化实践
前端性能直接影响用户体验和 SEO 排名。以下是系统性的优化策略。
加载性能
资源压缩
<!-- 压缩 CSS -->
<link rel="stylesheet" href="style.min.css">
<!-- 压缩 JS -->
<script src="app.min.js" defer></script>
图片优化
<!-- 使用 WebP 格式 -->
<picture>
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="描述" loading="lazy">
</picture>
预加载关键资源
<link rel="preload" href="font.woff2" as="font" crossorigin>
<link rel="preconnect" href="https://api.example.com">
渲染性能
避免布局抖动
/* 给图片预留空间 */
img {
aspect-ratio: 16 / 9;
width: 100%;
height: auto;
}
使用 CSS transforms 替代 top/left
/* 不好:触发布局 */
.box {
transition: top 0.3s;
}
.box:hover {
top: 10px;
}
/* 好:使用 transform */
.box {
transition: transform 0.3s;
}
.box:hover {
transform: translateY(10px);
}
虚拟滚动
长列表使用虚拟滚动,只渲染可见区域的元素。
缓存策略
| 资源类型 | Cache-Control |
|---|---|
| HTML | no-cache |
| CSS/JS(带 hash) | max-age=31536000 |
| 图片 | max-age=86400 |
总结
性能优化是一个系统工程,需要从加载、渲染、缓存多个维度综合考虑。