懒加载的实现过程

使用原生实现懒加载

实现原理

  1. 先把所有的图片都不显示出来
  2. 把地址放到自定义属性上保存起来
  3. 获取一些值(窗口文档图片)
    参考地址
<script>
	const div = document.querySelector('div')
    getList()
    function getList() {
      const xhr = new XMLHttpRequest
      xhr.open('get', '/list')
      xhr.onload = function () {
        console.log(xhr.responseText)
        // 拿到响应的数据,传入到回调函数
        bindHtml(JSON.parse(xhr.responseText))
      }
      xhr.send()
    }

    function bindHtml(list) {
      // 拿到数据,遍历数组中的每一项
      list.forEach(item => {
        // console.log(item)
        // 创建一个图片对象
        const img = new Image
        img.dataset.src = item.goods_big_logo
        div.appendChild(img)
      })
      lazyLoad()
      window.onscroll = function () {
        lazyLoad()
      }
    }
    function lazyLoad() {
      const imgs = document.querySelectorAll('img')
      // 窗口的高度
      const windowHeight = document.documentElement.clientHeight
      // 浏览器卷曲的高度
      const scrollY = window.scrollY
      imgs.forEach(item => {
        if (item.offsetTop - scrollY < windowHeight + 200) {
          // 我到了可是区域里面了
          item.src = item.dataset.src
        }
      })
    }
</script>

使用lazyload.js插件来写

<div></div>
<script src="https://cdn.jsdelivr.net/npm/lazyload@2.0.0-rc.2/lazyload.js"></script>
<script>
	const div = document.querySelector('div')
    getList()
    function getList() {
      const xhr = new XMLHttpRequest
      xhr.open('get', '/list')
      xhr.onload = function () {
        bindHtml(JSON.parse(xhr.responseText))
      }
      xhr.send()
    }

    function bindHtml(list) {
      list.forEach(item => {
        const img = new Image
        img.src = '/public/test.gif'
        img.dataset.src = item.goods_big_logo
        img.className = 'lazyload'
        div.appendChild(img)
      })

      lazyload()
    }
</script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值