亲宝软件园·资讯

展开

IntersectionObserver实现图片懒加载的示例

小小程序猿(^_^) 人气:0

API:

https:/https://img.qb5200.com/download-x/developer.mozilla.org/en-UShttps://img.qb5200.com/download-x/docs/Web/API/Intersection_Observer_API

直接上源码:

<!DOCTYPE html>
<html>
  <header>
    <style>
      .list-item{
        height: 400px; 
        margin: 5px; 
        background-color: lightblue; 
        list-style: none;
      }
    </style>
  </header>
  <body>
    <li class="list-item"><img class="list-item-img" alt="loading" data-src='./images/icon1.png'></li>
    <li class="list-item"><img class="list-item-img" alt="loading" data-src='./images/icon2.png'></li>
    <li class="list-item"><img class="list-item-img" alt="loading" data-src='./images/icon3.png'></li>
    <li class="list-item"><img class="list-item-img" alt="loading" data-src='./images/icon4.png'></li>
    <li class="list-item"><img class="list-item-img" alt="loading" data-src='./images/icon5.png'></li>
    <li class="list-item"><img class="list-item-img" alt="loading" data-src='./images/icon6.png'></li>

    <script>
      var observer = new IntersectionObserver(function(changes) {
        console.log(changes);
        changes.forEach(function(element, index) {
          // statements
          if (element.intersectionRatio > 0 && element.intersectionRatio <= 1) {
            element.target.src = element.target.dataset.src;
          }
        });
      });


      function addObserver() {
        var listItems = document.querySelectorAll('.list-item-img');
        listItems.forEach(function(item) {
          observer.observe(item);
        });
      }

      addObserver();
    </script>
  </body>
</html>

运行代码后发现,当滚动滚动轴时,只有当<li>区域完全显示出来后才会触发相应的下载图片的http请求。

兼容浏览器:

desktop:

Mobile:

以上这篇IntersectionObserver实现图片懒加载的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论