function lazyLoad() { const images = document.querySelectorAll('img[data-src]'); const iframes = document.querySelectorAll('iframe[data-src]'); const elements = [...images, ...iframes]; const observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { const element = entry.target; if (element.tagName === 'IMG') { element.src = element.dataset.src; } else if (element.tagName === 'IFRAME') { element.src = element.dataset.src; } observer.unobserve(element); } }); }); elements.forEach(element => observer.observe(element)); } document.addEventListener('DOMContentLoaded', lazyLoad);
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter