圖片懶加載

實現方案

  • 默認不加載圖片,僅加載佔位圖片
  • 計算圖片是否位於可視區域內,觸發加載條件
  • < img >src屬性加載資源

在計算圖片是否位於可視區域時,需要先了解

  • scollTop/offsetTop等,這篇博客有對這些偏移量的詳細解釋
  • 判斷方法:可視區域的高度(offsetHeight) + 滾動條捲去的高度(scrollTop) >= 元素相對於外框的距離(offsetTop) - 偏移量 (提前加載)

代碼實現

html:

<style type="text/css">
.container{
    width:200px;
    height:200px;
    position:relative;
    overflow-y:scroll;
}
.img-area{
    width:100px;
    height:100px;
}
</style>
<div class="container">
    <div class="img-area">
        <img class="pic" alt="loading" data-src="./img/img1.png" src="佔位圖片">
    </div>
    <div class="img-area">
        <img class="pic" alt="loading" data-src="./img/img2.png" src="佔位圖片">
    </div>
    <div class="img-area">
        <img class="pic" alt="loading" data-src="./img/img3.png" src="佔位圖片">
    </div>
    <div class="img-area">
        <img class="pic" alt="loading" data-src="./img/img4.png" src="佔位圖片">
    </div>
    <div class="img-area">
        <img class="pic" alt="loading" data-src="./img/img5.png" src="佔位圖片">
    </div>
</div>

data-src是自定義屬性,保存圖片的真實地址,src是佔位圖片的地址
js:

    var container = document.querySelector('.container');
    container.onscroll = function(){
        checkImgs();
    }
    function isInSight(el) {
        var sTop = container.scrollTop;
        var oHeight = container.offsetHeight;
        var oTop = el.offsetTop;
        return sTop + oHeight > oTop;
    }
    function checkImgs() {
      var imgs = document.querySelectorAll('.pic');
      Array.from(imgs).forEach(el => {
        if (isInSight(el)) {
          loadImg(el);
        }
      })
    }
    function loadImg(el) {
        var source = el.dataset.src;
        el.src = source;
    }
        checkImgs();

待優化部分:

  • onscroll會多次觸發回調函數,應設置節流函數
  • 在計算時,增加偏移數據,提前加載圖片,提升用戶體驗

其他思路

  • 使用IntersectionObserver(html5 API)
  • 利用分頁(底部loading標籤)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章