API:
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
Go directly to the source code :
<!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>
After running the code, I found that when the scroll axis is scrolled, the corresponding action will only be triggered when the
Compatible browsers:
desktop:
Mobile:
The above is the detailed content of How to use IntersectionObserver to implement lazy loading of images. For more information, please follow other related articles on the PHP Chinese website!