[Javascript] Intersectionobserver--Lazy Load Images on a Website

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.