[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

 

We can add some Margin to preload image even before we scroll to the image:

复制代码
          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)
                  }
              })
          }, {
             rootMargin: '50px'
          })    
复制代码

rootMargin  Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). The values can be percentages. This set of values serves to grow or shrink each side of the root element's bounding box before computing intersections. Defaults to all zeros.

posted @   Zhentiw  阅读(319)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-05-08 [CSS] Draw Simple Icons with CSS
2017-05-08 [CSS] Reduce Ambiguity in Class Names using a Naming Convention
点击右上角即可分享
微信分享提示