Skip to content

Instantly share code, notes, and snippets.

@PechenkiUA
Created September 15, 2022 08:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PechenkiUA/9cff3a393dcbf757c16750b990d12337 to your computer and use it in GitHub Desktop.
Save PechenkiUA/9cff3a393dcbf757c16750b990d12337 to your computer and use it in GitHub Desktop.
lazy load src element video,source,iframe
function isInViewport(el) {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
document.addEventListener('scroll', LLoad, {
passive: true
});
function LLoad(){
document.querySelectorAll('video,source,iframe').forEach(item=>{
if (item.dataset.src && isInViewport(item)){
item.src = item.dataset.src
item.removeAttribute('data-src')
}
})
}
LLoad()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment