DEMO – https://codepen.io/ktr92/pen/qBGqRgZ
html example
<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
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)
})
}
document.addEventListener(‘DOMContentLoaded’, function() {
lazyLoadSrc(‘img’);
lazyLoadSrc(‘iframe’);
})