本文主要为大家带来一篇IntersectionObserver实现图片懒加载的示例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。
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" src='./images/icon1.png'></li> <li class="list-item"><img class="list-item-img" alt="loading" src='./images/icon2.png'></li> <li class="list-item"><img class="list-item-img" alt="loading" src='./images/icon3.png'></li> <li class="list-item"><img class="list-item-img" alt="loading" src='./images/icon4.png'></li> <li class="list-item"><img class="list-item-img" alt="loading" src='./images/icon5.png'></li> <li class="list-item"><img class="list-item-img" alt="loading" 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>
运行代码后发现,当滚动滚动轴时,只有当25edfb22a4f469ecb59f1190150159c6区域完全显示出来后才会触发相应的下载图片的http请求。
兼容浏览器:
desktop:
Mobile:
相关推荐:
以上是Intersection Observer图片懒加载实现方法的详细内容。更多信息请关注PHP中文网其他相关文章!