name: 图像优化
description: 使用现代格式、响应式技术和懒加载策略优化图像以提升网页性能。适用于改善页面加载时间、实现响应式图像或为生产部署准备资源。
license: MIT
图像优化
使用现代格式和响应式技术优化图像以提升网页性能。
格式选择
| 格式 |
最佳用途 |
压缩率 |
| JPEG |
照片 |
有损压缩,减少50-70% |
| PNG |
图标、透明背景 |
无损压缩,减少10-30% |
| WebP |
现代浏览器 |
比JPEG好25-35% |
| AVIF |
下一代格式 |
比JPEG好50% |
| SVG |
标志、图标 |
矢量,可缩放 |
响应式图像
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img
src="image.jpg"
srcset="image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw, 50vw"
alt="描述"
loading="lazy"
decoding="async"
>
</picture>
懒加载
<!-- 原生懒加载 -->
<img src="image.jpg" loading="lazy" alt="描述">
<!-- 带模糊占位符 -->
<img
src="placeholder-blur.jpg"
data-src="image.jpg"
class="lazy"
alt="描述"
>
构建管道 (Sharp)
const sharp = require('sharp');
async function optimizeImage(input, output) {
await sharp(input)
.resize(1200, null, { withoutEnlargement: true })
.webp({ quality: 80 })
.toFile(output);
}
性能目标
| 资产类型 |
目标大小 |
| 主图 |
<200KB |
| 缩略图 |
<30KB |
| 总图像 |
<500KB |
优化清单
- [ ] 使用WebP并提供JPEG回退
- [ ] 实现响应式srcset
- [ ] 为下方内容启用懒加载
- [ ] 以质量70-85压缩
- [ ] 从CDN提供服务
- [ ] 设置适当的缓存头