Skip to content

Instantly share code, notes, and snippets.

@patrickallaert
Created February 25, 2019 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickallaert/02729fca817e44342b7d9861ea9494d3 to your computer and use it in GitHub Desktop.
Save patrickallaert/02729fca817e44342b7d9861ea9494d3 to your computer and use it in GitHub Desktop.
defer image loading
document.addEventListener("DOMContentLoaded", function() {
const srcDeferAttribute = "data-defer";
const srcBackingAttribute = "data-deferred";
document.querySelectorAll("*[" + srcDeferAttribute + "]").forEach(function(lazyImage) {
if (!lazyImage.complete) {
lazyImage.setAttribute(srcBackingAttribute, lazyImage.getAttribute("src"));
lazyImage.setAttribute("src", "data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=");
}
lazyImage.removeAttribute(srcDeferAttribute);
});
let lazyImages = [].slice.call(document.querySelectorAll("*[" + srcBackingAttribute + "]"));
let active = false;
const lazyLoad = function() {
if (active === false) {
active = true;
setTimeout(function() {
lazyImages.forEach(function(lazyImage) {
if ((lazyImage.getBoundingClientRect().top <= window.innerHeight && lazyImage.getBoundingClientRect().bottom >= 0) && getComputedStyle(lazyImage).display !== "none") {
lazyImage.setAttribute("src", lazyImage.getAttribute(srcBackingAttribute));
lazyImage.removeAttribute(srcBackingAttribute);
lazyImages = lazyImages.filter(function(image) {
return image !== lazyImage;
});
if (lazyImages.length === 0) {
document.removeEventListener("scroll", lazyLoad);
window.removeEventListener("resize", lazyLoad);
window.removeEventListener("orientationchange", lazyLoad);
}
}
});
active = false;
}, 200);
}
};
lazyLoad();
document.addEventListener("scroll", lazyLoad);
window.addEventListener("resize", lazyLoad);
window.addEventListener("orientationchange", lazyLoad);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment