图片懒加载是怎么实现的?
参考答案
1. IntersectionObserver(推荐)
const io = new IntersectionObserver(entries => {
entries.forEach(en => {
if (en.isIntersecting) { en.target.src = en.target.dataset.src; io.unobserve(en.target); }
});
}, { rootMargin: '200px' });
document.querySelectorAll('img[data-src]').forEach(i => io.observe(i));
2. scroll + 计算(兼容老环境)
监听滚动(节流/rAF),判断 img.getBoundingClientRect().top < innerHeight + offset 再加载。
3. 原生
<img loading="lazy">(简单有效,无法精细控制)。
要点
- 用
data-src占位,配小图/纯色占位防跳动(固定宽高比); - 加载后切换 src 并移除监听;
- 处理加载失败兜底图;
- 首屏图不懒加载(影响 LCP),并加
fetchpriority。