懶加載——lazyload

在聲明img元素時(shí),只需要將其圖片地址放到data-src中,并且聲明class="lazyload"即可實(shí)現(xiàn)圖片的懶加載效果。
示例:

<img data-src="https://xxxxxx.com?sjdijsa" class="lazyload">
<img data-src="https://xxxxxx.com?sjdijsa" class="lazyload">

調(diào)用lazyload函數(shù),并傳入?yún)?shù)。

  • 第一個(gè)參數(shù)表示所有的img標(biāo)簽,可以根據(jù)具體的元素進(jìn)行調(diào)整
  • 第二個(gè)參數(shù)表示圖片距離視口多少距離
lazyload(document.querySelectorAll('img'),0)

以下為實(shí)現(xiàn)的源碼。
具體思路:每次觸發(fā)scroll事件時(shí)(節(jié)流),找到所有含有class為lazyload的img標(biāo)簽。遍歷所有標(biāo)簽,判斷是否符合加載的要求,完成渲染。

lazyload(document.querySelectorAll('img'),0)

function lazyload(images,distance){
  imgs = Array.from(images)

  if('IntersectionObserver' in window){
    let observer = new IntersectionObserver(function(entries){
      entries.forEach(entry=>{
        loadImage(entry.target,()=>{
          observer.unobserve(entry.target)
        })
      })
    },{threshold: 0.01})
    imgs.forEach(img=>observer.observe(img))
  }else{
    document.onscroll = throttle(function(){
      imgs = imgs.filter(img=>img.classList.contains('lazyload'))
      imgs.forEach(img=>{
        if(imgView(img,distance)){
          loadImage(img)
        }
      })
    },200)
    document.dispatchEvent(new Event('scroll'))
  }
  function throttle(fn,wait){
    let lastTime = null
    let nowTime = null
    return function(){
      nowTime = new Date()
      if(!lastTime || nowTime - lastTime > wait){
        fn.apply(this,arguments)
        lastTime = nowTime
      }
    }
  }
  
  function imgView(img,distance){
    let { top } = img.getBoundingClientRect()
    let viewHeight = document.documentElement.clientHeight
    return top>0 && top<viewHeight+distance
  }
  
  function loadImage(img,callback){
    let image = new Image()
    image.src = img.dataset.src
    image.onload = function(){
      img.src = image.src
      img.classList.remove('lazyload')
      callback()
    }
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容