优化

122 阅读1分钟

图片懒加载

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .image-item {
        display: block;
        margin: 0 auto 50px auto;
        /* 一定记得设置图片高度 */
        height: 200px;
      }
    </style>
  </head>

  <body>
    <img
      src=""
      class="image-item"
      lazyload="true"
      data-original="https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1015613717,2953594052&fm=26&gp=0.jpg"
    />
    <!-- ..调试时复制img即可 -->
    <script>
      // 获取可视区高度
      const viewHeight = document.documentElement.clientHeight;
      function lazyload() {
        // 获取没有加载的图片
        const notLoads = document.querySelectorAll(
          "img[data-original][lazyload]"
        );
        Array.prototype.forEach.call(notLoads, function (item, index) {
          // 用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置
          const rect = item.getBoundingClientRect();
          if (rect.bottom >= 0 && rect.top < viewHeight) {
            console.log(item); // 屏幕滚动打印出加载的图片
            item.src = item.dataset.original;
            // 移除属性,下次不再遍历
            item.removeAttribute("lazyload");
          }
        });
      }
      // 刚开始还没滚动屏幕时,要先触发一次函数,初始化首页的页面图片
      lazyload();
      document.addEventListener("scroll", lazyload);
    </script>
  </body>
</html>

懒加载的原理

首先将页面上的图片的 src 属性设为空字符串,而图片的真实路径则设置在data-original属性中, 当页面滚动的时候需要去监听scroll事件,在scroll事件的回调中,判断我们的懒加载的图片是否进入可视区域,如果图片在可视区内将图片的 src 属性设置为data-original 的值,这样就可以实现延迟加载。