图片懒加载指南
方法一:原生loading="lazy"(推荐)
浏览器支持率:92%+。无需JavaScript。
<!-- Always set width and height to prevent layout shift --> <img src="photo.webp" loading="lazy" width="800" height="600" alt="Description of image" > <!-- Do NOT lazy-load the LCP image (above the fold) --> <img src="hero.webp" loading="eager" fetchpriority="high" ...>
方法二:Intersection Observer API
更多控制——自定义阈值、动画效果、兜底处理。
// HTML: use data-src instead of src
// <img class="lazy" data-src="photo.webp" alt="...">
const lazyImages = document.querySelectorAll('img.lazy');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove('lazy');
observer.unobserve(img);
}
});
}, {
rootMargin: '200px 0px', // load 200px before visible
threshold: 0
});
lazyImages.forEach(img => observer.observe(img));
模糊渐显 / LQIP技术
/* CSS: show a tiny blurred placeholder */
.lazy-wrapper {
position: relative;
overflow: hidden;
}
.lazy-placeholder {
filter: blur(20px);
transform: scale(1.05); /* hide blur edges */
transition: opacity 0.4s;
}
.lazy-loaded .lazy-placeholder {
opacity: 0;
}
快速参考
| 方法 | 浏览器支持 | 需要JS | 自定义偏移 |
|---|---|---|---|
| loading="lazy" | 92%+ | 否 | 否 |
| Intersection Observer | 97%+ | 是 | 是 |
| 库(lazysizes) | 全部 | 是(5KB) | 是 |