页面滚动时,图片露出,将data-src赋值给src 滚动要节流 获取图片定位 元素的位置ele.getBoundingClientRect 图片top > window.innerHeight没有露出,top <...">第143题 设计实现一个H5图片懒加载 | 前端面试题集锦 页面滚动时,图片露出,将data-src赋值给src 滚动要节流 获取图片定位 元素的位置ele.getBoundingClientRect 图片top > window.innerHeight没有露出,top <...">

第143题 设计实现一个H5图片懒加载

  • 分析
    • 定义 <img src="loading.png" data-src="xx.png" />
    • 页面滚动时,图片露出,将data-src赋值给src
    • 滚动要节流
  • 获取图片定位
    • 元素的位置ele.getBoundingClientRect
    • 图片top > window.innerHeight没有露出,top < window.innerHeight露出
    <!-- 图片拦截加载 -->
    <div class="item-container">
      <p>新闻标题</p>
      <img src="./img/loading.gif" data-src="./img/animal1.jpeg"/>
    </div>
    <div class="item-container">
      <p>新闻标题</p>
      <img src="./img/loading.gif" data-src="./img/animal2.webp"/>
    </div>
    <div class="item-container">
      <p>新闻标题</p>
      <img src="./img/loading.gif" data-src="./img/animal3.jpeg"/>
    </div>
    <div class="item-container">
      <p>新闻标题</p>
      <img src="./img/loading.gif" data-src="./img/animal4.webp"/>
    </div>
    <div class="item-container">
      <p>新闻标题</p>
      <img src="./img/loading.gif" data-src="./img/animal5.webp"/>
    </div>
    <div class="item-container">
      <p>新闻标题</p>
      <img src="./img/loading.gif" data-src="./img/animal6.webp"/>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
    <script>
      function mapImagesAndTryLoad() {
        const images = document.querySelectorAll('img[data-src]')
        if (images.length === 0) return
    
        images.forEach(img => {
          const rect = img.getBoundingClientRect()
          if (rect.top < window.innerHeight) {
            // 漏出来
            // console.info('loading img', img.dataset.src)
            img.src = img.dataset.src
            img.removeAttribute('data-src') // 移除 data-src 属性,为了下次执行时减少计算成本
          }
        })
      }
    
      // 滚动需要节流
      window.addEventListener('scroll', _.throttle(() => {
        mapImagesAndTryLoad()
      }, 100))
    
      // 初始化默认执行一次
      mapImagesAndTryLoad()
    </script>
Last Updated:
Contributors: leeguooooo