懒加载——lazyload

在声明img元素时,只需要将其图片地址放到data-src中,并且声明class="lazyload"即可实现图片的懒加载效果。
示例:

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

调用lazyload函数,并传入参数。

  • 第一个参数表示所有的img标签,可以根据具体的元素进行调整
  • 第二个参数表示图片距离视口多少距离
lazyload(document.querySelectorAll('img'),0)

以下为实现的源码。
具体思路:每次触发scroll事件时(节流),找到所有含有class为lazyload的img标签。遍历所有标签,判断是否符合加载的要求,完成渲染。

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()
    }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容