第一种,可视区域高度对比

通过获取可视区域的高度,document.ducoumentElement.clientHeight,和当前Image元素的

  1. const bufferHeight = 600;
  2. const clientHeight = document.documentElement.clientHeight;
  3. const isInVisible = (imgNode)=>{
  4. const imgRect = imgNode.getBoundingClientRect();
  5. return imgRect.top > clientHeight && imgRect.top - bufferHeight < clientHeight&& !imgNode.getAttribute("src");
  6. };
  7. let isFinished = true;
  8. imagesNode.forEach((imgNode) => {
  9. if(!imgNode.getAttribute("src")) {
  10. isFinished = false;
  11. }
  12. if(isInVisible(imgNode)) {
  13. imgNode.setAttribute("src", imgNode.dataset.src);
  14. }
  15. });
  16. if(isFinished) {
  17. document.removeEventListener("scroll",loadInvisibleImg);
  18. }

第二种,intersectionObserver

  1. var imageObserver = new IntersectionObserver(function(entries, observer) {
  2. entries.forEach(function(entry) {
  3. // 图片是否进入视窗
  4. if (entry.isIntersecting) {
  5. var image = entry.target;
  6. image.src = image.dataset.src;
  7. imageObserver.unobserve(image);
  8. }
  9. });
  10. });
  11. // 将观察者注册到所有图片上
  12. imagesNode.forEach(function(image) {
  13. imageObserver.observe(image);
  14. });

image.png

第三种, lazyload属性