懒加载

May 08, 2022

如何实现图片懒加载

使用img lazyloading属性

缺点: 兼容性不好

IntersectionObserver + data set

IntersectionObserver 能够监听元素是否到了当前视窗,再动态设置元素的src

const observer = new IntersectionObserver((changes) => {
  // changes: 目标元素集合
  changes.forEach((change) => {
    // intersectionRatio
    if (change.isIntersecting) {
      const img = change.target;
      img.src = img.dataset.src;
      observer.unobserve(img);
    }
  });
});

observer.observe(img);

getBoundingClientRect + Scroll + data set

如何判断图片出现在了当前窗口

img.getBoundingClientRect().top < document.documentElement.clientHeight;

监听window.scroll事件,动态设置img的src


Profile picture

百事可乐

Let it snow, let it snow, let it snow