實現懶加載的幾種方式(二)

上一篇文章介紹了實現圖片懶加載的第一種方式:圖片到瀏覽器頂部的距離offsetTop< 視口高度clientHeight+滾動軸距離scrollTop。 下面介紹實現懶加載的第二種方式,經過getBoundingClientRect這個API實現。html

1. 實現原理

  • getBoundClientRect介紹

Element.getBoundingClientRect() 方法返回元素的大小及其相對於視口的位置。咱們能夠取得它的top值,它的top值就是元素左上角到視口頂部的距離。git

  • 加載的條件

Element.getBoundingClientRect().top < 視口高度時觸發加載;github

2. 代碼實現

  • html結構和CSS樣式
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    img {
      height: 450px;
      display: block;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
  <!--圖片地址暫時先保存在data-src這個自定義屬性上面-->
  <img data-src="./img-loop/img/1.jpg" alt="懶加載1" />
  <img data-src="./img-loop/img/2.png" alt="懶加載2" />
  <img data-src="./img-loop/img/3.jpg" alt="懶加載3" />
  <img data-src="./img-loop/img/4.jpg" alt="懶加載4" />
  <img data-src="./img-loop/img/5.jpg" alt="懶加載5" />
</body>
</html>
複製代碼
  • js代碼
const imgs = document.getElementsByTagName('img');
    // 判斷元素是否出如今視口內
    function isShow(el) {
      // 視口高度
      const clientH = window.innerHeight;
      const bound = el.getBoundingClientRect();
      // 判斷元素左上角到視口頂部的距離是否小於視口高度
      return bound.top < clientH;
    };

    // 加載圖片
    function showImg(el) {
      if(!el.src) {
        el.src = el.dataset.src;
      }
    }

    // 懶加載
    function lazyLoad() {
      console.log('加載了');
      [...imgs].forEach(el => {
        if(isShow(el)) {
          showImg(el);
        }
      })
    };

    lazyLoad();

    // 節流函數
    function throttle(fn, delay) {
      let timer = null;
      return () => {
        if(timer) {
          return;
        };
        timer = setTimeout(() => {
          fn(imgs);
          timer = null;
        }, delay);
      }
    };

    window.onscroll = throttle(lazyLoad, 500);
複製代碼

3. 效果


所有代碼瀏覽器

下一篇:懶加載的第三種實現方式bash

相關文章
相關標籤/搜索