本文主要為大家帶來一篇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中文網其他相關文章!