DEV Community

ktr92
ktr92

Posted on

VanillaJS Lazy Load images/video/embed/youtube

DEMO - https://codepen.io/ktr92/pen/qBGqRgZ

html example

<img data-src='https://placehold.co/600x400'>
<iframe width="560" height="315" data-src="https://www.youtube.com/embed/NpEaa2P7qZI?si=4Rq1E37zRobyhGRI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
Enter fullscreen mode Exit fullscreen mode

JS

function lazyLoadSrc(selector) {
  const callback = (entries, observer) => {
    entries.forEach(entry => {
      const source = entry.target
      if (entry.intersectionRatio > 0) {
        if (!source.getAttribute('src')) {
            source.setAttribute('src', source.dataset.src)
            observer.unobserve(source)
        }
      }
    })
  }
  const target = document.querySelectorAll(selector)
  const options = {
    threshold: 0.4
  }
  let obs = new IntersectionObserver(callback, options)
  target.forEach(item => {
    obs.observe(item)
  }) 
}
Enter fullscreen mode Exit fullscreen mode
// usage
document.addEventListener('DOMContentLoaded', function() {
  lazyLoadSrc('img');
  lazyLoadSrc('iframe');
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)