通过 img 标签
1 2 3 4 5 6 7
| <div style={{ height: '300px', overflow: 'auto'}}> {items.map(item => ( <div key={item.id}> <img src={item.src} loading="lazy" decoding="async" /> </div> ))} </div>
|
这里使用 react 来做实例,items 是一个图片数组,我们给 img 标签的 loading 属性设置 “lazy” 来开启懒加载。需要注意的是该属性在浏览器的兼容性
滚动上去的高度 + 浏览器可视区高度 >= 图片距离文档顶部的高度
1 2 3 4 5 6 7 8
| <img data-src="img/1.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/2.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/3.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/4.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/5.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/6.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/7.jpg" src="img/0.png" alt="xxx" /> <img data-src="img/8.jpg" src="img/0.png" alt="xxx" />
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| var images = document.getElementsByTagName("img"); window.addEventListener("scroll", (e) => { ergodic(); }); function ergodic() { for (let i of images) { if (i.offsetTop <= window.innerHeight + window.scrollY) { let trueSrc = i.getAttribute("data-src"); i.setAttribute("src", trueSrc); } } } ergodic();
|
使用 Intersection Observer API
首先,在页面中将所有需要懒加载的图片的 src 属性设置为占位符或者一个小的loading图。
使用 Intersection Observer API 来监测图片元素是否进入了可视区域,并在图片进入可视区域时加载真实的图片。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <img data-src="image.jpg" class="lazy-load" alt="Lazy-loaded image">
<script> const lazyImages = document.querySelectorAll('.lazy-load');
const lazyLoad = target => { const io = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { const img = entry.target; const src = img.getAttribute('data-src');
img.setAttribute('src', src); observer.disconnect(); } }); });
io.observe(target); };
lazyImages.forEach(lazyLoad); </script>
|
在这个示例中,我们首先将需要懒加载的图片的真实路径存储在 data-src 属性中,
并添加一个具有 lazy-load 类名的标记。然后使用 JavaScript 遍历所有具有 lazy-load 类名的图片元素,
对每个图片元素应用 Intersection Observer,一旦图片元素进入视口(即可见),就将 data-src 的值赋给 src 属性以加载真实的图片。