Lazy Load Vanilla JS Script

PHOTO EMBED

Mon Oct 14 2024 10:32:36 GMT+0000 (Coordinated Universal Time)

Saved by @cbmontcw

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);
content_copyCOPY

https://www.google.com/search?q