码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-05-08 22:22:29      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:server   cse   query   inter   reac   blank   diff   The   span   

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

标签:server   cse   query   inter   reac   blank   diff   The   span   

原文地址:https://www.cnblogs.com/Answer1215/p/9010725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!