VanillaJS Lazy Load images/video/embed/youtube

VanillaJS Lazy Load images/video/embed/youtube

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

html example

<img data-src=’https://placehold.co/600×400′>
<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>

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)
})
}
// usage
document.addEventListener(‘DOMContentLoaded’, function() {
lazyLoadSrc(‘img’);
lazyLoadSrc(‘iframe’);
})
Please follow and like us:
Pin Share