Created
September 15, 2022 08:58
-
-
Save PechenkiUA/9cff3a393dcbf757c16750b990d12337 to your computer and use it in GitHub Desktop.
lazy load src element video,source,iframe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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