[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 CSSmargin
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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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