When it comes to websites performance was king. How long it takes-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 if an image is in the viewport to defer loading the image.
Document.addeventlistener (' domcontentloaded ', () ={Const Lazyimages= Array.from (Document.queryselectorall (' Img.lazy '))); if(' Intersectionobserver 'inchWindow && ' Intersectionobserverentry 'inchWindow && ' Intersectionratio 'inchwindow. Intersectionobserverentry.prototype) {//Define The ObserverLet Lazyimageobserver =NewIntersectionobserver (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 observeLazyimages.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