Intersection Observer API 实现图片懒加载

发布时间 2023-05-06 17:33:17作者: 神经蛙

1,为需要延迟加载的图片设置data-src属性。

<img src="" data-src="image.jpg" alt="图片">

2,使用Intersection Observer API监听可视区域内的元素变化,并将其data-src属性值赋给src属性,显示图片。

const lazyLoadImg = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      const imgElem = entry.target;
      imgElem.src = imgElem.dataset.src;
      lazyLoadImg.unobserve(imgElem);
    }
  });
});

document.querySelectorAll('img[data-src]').forEach(img => {
  lazyLoadImg.observe(img);
});

3,初始时需调用一次,以显示页面已经在可视区域内的图片。

document.querySelectorAll('img[data-src]').forEach(img => {
  if (img.getBoundingClientRect().top <= window.innerHeight && img.getBoundingClientRect().bottom >= 0) {
    img.src = img.dataset.src;
    img.removeAttribute('data-src');
  }
});

通过这些步骤,就可以实现图片的懒加载效果。需要注意的是,在这个方法中我们使用了Intersection Observer API来监听可视区域内元素的变化,并使用getBoundingClientRect()方法获取元素相对于视窗的位置信息。