Lazy Load Images with IntersectionObserver
Lazy Load Images with IntersectionObserver is a reusable JavaScript snippet. Uses the Intersection Observer API to detect when elements enter the viewport — perfect for lazy loading images, infinite scroll, and animations. The full implementation: function onVisible(element, callback, options = {}) { const observer = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) { callback(entry.target) observer.unobserve(entry.target) } }, { threshold: 0.1, ...options }) observer.observe(element) return () => observer.disconnect() } // Lazy load images function lazyLoadImages() { document.querySelectorAll('img[data-src]').forEach(img => { onVisible(img, el => { el.src = el.dataset.src el.removeAttribute('data-src') }) }) } // Infinite scroll function infiniteScroll(loadMore) { const sentinel = document.createElement('div') document.body.appendChild(sentinel) return onVisible(sentinel, () => loadMore(), { threshold: 0 }) } // Usage // lazyLoadImages() This snippet uses only standard JavaScript with no dependencies, so it runs in modern browsers and Node.js alike. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.