两种方法实现图片懒加载

2024/8/17 | 字数检测:1565
AI摘要

文章介绍了两种图片懒加载方法。第一种是利用Element.getBoundingClientRect,通过判断图片元素相对于视口的位置来动态加载图片,并监听滚动事件。第二种是利用Intersection Observer API,通过创建观察器来监听图片元素是否进入视口,一旦进入则加载图片。两种方法都将图片的真实地址预存在data-src中,并在图片进入视口时将其赋值给src属性。

废话不多说,直接进入正题,代码时刻

  1. 利用Element.getBoundingClientRect 该接口主要是获得元素相对于视口的位置,以及元素本身大小,我们可以根据位置信息判断图片所在元素是否出现在了视图中,从而来动态加载图片,我们已经提前把图片的资源地址设置在了data-src中,可以利用imgElement.dataset.src来获取
let imgList = [...document.querySelectorAll("img")];

const imgLazyLoad = function () {
  let deleteIndexList = [];
  imgList.forEach((img, index) => {
    let rect = img.getBoundingClientRect();
    if (rect.top < window.innerHeight) {
      img.src = img.dataset.src;
      deleteIndexList.push(index);
    }
  });
  imgList = imgList.filter((img, index) => !deleteIndexList.includes(index));
  //滚动到底部后,移除滚动监听
  if (imgList.length === 0) {
    document.removeEventListener("scroll", imgLazyLoad);
  }
};

document.addEventListener("scroll", imgLazyLoad);
  1. 利用Intersection Observer API 其实很类似,使用 intersectionObserver 的实例,使用observer()方法来添加每一个元素的观察每一个元素,只要出现在视口中我们就开始加载图片
const createObserver = () => {
  const options = {
    // 默认root为null或者不设置,默认为视口
    root: null,
    // 可增加根元素参考边距
    rootMargin: "0px",
    // 阈值(目标元素出现内容相对与根元素的百分比)(0-1.0)
    // 1.0意味着元素完全出现在根元素中,才会执行回调函数
    threshold: 0,
  };

  const observer = new IntersectionObserver(loadImg, options);
  const imgs = document.querySelectorAll("img");
  // 可添加多个观察对象,我们把所有图片元素添加进去
  for (const img of imgs) {
    observer.observe(img);
  }
};

const loadImg = (entries, observe) => {
  entries.forEach((entry) => {
    const ele = entry.target;
    // 目标元素进入根元素
    if (entry.isIntersecting && !ele.src) {
      ele.src = ele.dataset.src;
    }
  });
};
// 开启交叉观察
createObserver();
更新时间:2024/8/17