IntersectionObserver实现图片懒加载的示例
程序员文章站
2022-07-06 21:02:58
api:
https://developer.mozilla.org/en-us/docs/web/api/intersection_observer_api
直接上源...
api:
https://developer.mozilla.org/en-us/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实现图片懒加载的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。