Skip to content

Instantly share code, notes, and snippets.

@abdullahoguk
Last active March 4, 2021 08:19
Show Gist options
  • Save abdullahoguk/dc1a37c058d75c42e10e2239bfeab23e to your computer and use it in GitHub Desktop.
Save abdullahoguk/dc1a37c058d75c42e10e2239bfeab23e to your computer and use it in GitHub Desktop.
Vanilla Lazy Load
//source: https://www.merixstudio.com/blog/lazy-loading-pure-javascript/
function lazyLoadInit(){
let lazyImages = [].slice.call(document.querySelectorAll("img.lazy"));
let active = false;
var treshold = 100;
const lazyLoad = function() {
if (active === false) {
active = true;
setTimeout(function() {
lazyImages.forEach(function(lazyImage) {
if ((lazyImage.getBoundingClientRect().top-treshold <= window.innerHeight && lazyImage.getBoundingClientRect().bottom+treshold >= 0)) {
lazyImage.src = lazyImage.dataset.src;
lazyImage.classList.remove("lazy");
lazyImages = lazyImages.filter(function(image) {
return image !== lazyImage;
});
if (lazyImages.length === 0) {
document.removeEventListener("scroll", lazyLoad);
window.removeEventListener("orientationchange", lazyLoad);
}
}
});
active = false;
}, 200);
}
};
document.addEventListener("scroll", lazyLoad);
window.addEventListener("resize", lazyLoad);
window.addEventListener("orientationchange", lazyLoad);
document.dispatchEvent(new CustomEvent('scroll'))
}
AddOnLoadEvent(lazyLoadInit);
/*
//ADD TO ON LOAD EVENT
function AddOnLoadEvent(functionX) {
var oldonloadevent = window.onload;
if (typeof window.onload != 'function') {
window.onload = functionX;
}
else {
window.onload = function () {
if (oldonloadevent) {
oldonloadevent();
}
functionX();
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment