[Javascript] IntersectionObserver -- Lazy Load Images on a Website
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript] IntersectionObserver -- Lazy Load Images on a Website相关的知识,希望对你有一定的参考价值。
When it comes to websites performance is king. How long it takes for a page to load can mean the difference of millions of dollars for large ecommerce sites. In this lesson we‘ll use the IntersectionObserver to check when an image is in the viewport to defer loading the image.
document.addEventListener(‘DOMContentLoaded‘, () => { const lazyImages = Array.from(document.querySelectorAll(‘img.lazy‘)); if (‘IntersectionObserver‘ in window && ‘IntersectionObserverEntry‘ in window && ‘intersectionRatio‘ in window.IntersectionObserverEntry.prototype) { // Define the observer let lazyImageObserver = new IntersectionObserver((entries, observer) => { entries.forEach((entry) => { // logic for handling interstion if (entry.isIntersecting) { let lazyImage = entry.target lazyImage.src = lazyImage.dataset.src lazyImage.srcset = lazyImage.dataset.srcset lazyImage.classList.remove(‘lazy‘) lazyImageObserver.unobserve(lazyImage) } }) }) // What to observe lazyImages.forEach(lazyImage => { lazyImageObserver.observe(lazyImage) }) } else { } })
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API/Timing_element_visibility
以上是关于[Javascript] IntersectionObserver -- Lazy Load Images on a Website的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 349 Intersection of Two Arrays & 350 Intersection of Two Arrays II