图片懒加载+函数节流(js简单实现)

顶部的图片是用来表示刷新页面的时候如果图片已经出现在可视范围内(这时候还没触发 scroll 事件),需要给他们进行一次加载

<!DOCTYPE html>

<style>
  article {
    height: 2000px;
  }

  footer {
    height: 2000px;
  }

  .panel {
    position: fixed;
    top: 0;
    right: 0;
    width: 300px;
  }

  .img {
    display: flex;
    justify-content: center;
  }
</style>

<html>

<body>
  <div class="img">
    <img src="http://via.placeholder.com/500x500" alt="">
  </div>
  <article></article>
  <div class="panel">
    <p class="item"></p>
    <p class="item"></p>
    <p class="item"></p>
    <p class="item"></p>
    <p class="item"></p>
  </div>
  <div class="img">
    <img src="http://via.placeholder.com/500x500" alt="">
  </div>
  <footer></footer>
</body>

</html>

<script>
  // 获取 DOM 对象
  const img = document.querySelector('.img img')
  const items = document.querySelectorAll('.panel>.item')

  lazyLoadingInit([img])
  // 函数节流
  const throttledLazyLoading = throttled(lazyLoading)
  window.addEventListener('scroll', () => {
    throttledLazyLoading([img])
  })


  /**
   * @param {Array} imageList
   * 
   * 图片懒加载初始化
   **/
  function lazyLoadingInit(imageList) {
    imageList.forEach(item => {
      if (item.offsetTop < document.documentElement.clientHeight) {
        items[4].innerHTML = `图片初始化成功!`
      }
    })
  }

  /**
   * @param {Array} imageList
   * 
   * 图片懒加载
   **/
  function lazyLoading(imageList) {
    // window.addEventListener('scroll', () => {
    let o = img.offsetTop
    let s = document.documentElement.scrollTop
    let c = document.documentElement.clientHeight

    let top = img.getBoundingClientRect().top

    items[0].innerHTML = `offsetTop = ${o}`
    items[1].innerHTML = `scrollTop = ${s}`
    items[2].innerHTML = `clientHeight = ${c}`
    items[3].innerHTML = `top = ${top}`
    // 方法一:clientHeight + scrollTop > offsetHeight
    // if (c + s > o) {
    //   items[4].innerHTML = `图片加载成功!`
    // }

    // 方法二:bound.top < clientHeight
    if (top < c) {
      items[4].innerHTML = `图片加载成功!`
    }
    // })
  }

  /**
   * @param {Function} fn 待装饰函数
   * @param {number} delay 重复触发判定时间
   * 
   * 函数节流
   **/
  function throttled(fn, delay = 500) {
    let timer = null
    return function (...args) {
      if (!timer) {
        timer = setTimeout(() => {
          fn.apply(null, args)
          timer = null
        }, delay)
      }
    }
  }
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值