Skip to content

Instantly share code, notes, and snippets.

@tristolliday
Created April 26, 2021 10:48
Show Gist options
  • Select an option

  • Save tristolliday/b3367e6a6238c3b0b0e260a8885262bf to your computer and use it in GitHub Desktop.

Select an option

Save tristolliday/b3367e6a6238c3b0b0e260a8885262bf to your computer and use it in GitHub Desktop.
$(document).ready(function () {
var lazyloadBgImages = document.querySelectorAll(".lazybg");
if ("IntersectionObserver" in window) {
var bgImageObserver = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
var image = entry.target;
image.style["background-image"] = "url('" + image.dataset.bgsrc + "')";
image.classList.remove("lazybg");
bgImageObserver.unobserve(image);
}
});
});
lazyloadBgImages.forEach(function (image) {
bgImageObserver.observe(image);
});
} else {
var lazyloadThrottleTimeout;
document.addEventListener("scroll", lazyload(lazyloadBgImages));
window.addEventListener("resize", lazyload(lazyloadBgImages));
window.addEventListener("orientationChange", lazyload(lazyloadBgImages));
}
var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
console.log("ie11= " + isIE11);
if (isIE11) {
lazyloadBgImages.forEach(function (bgelement) {
bgelement.style["background-image"] = "url('" + bgelement.dataset.bgsrc + "')";
bgelement.classList.remove('lazybg');
});
}
function lazyload(lazyloadBgImages) {
if (lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function () {
var scrollTop = window.pageYOffset;
lazyloadBgImages.forEach(function (bgelement) {
if (bgelement.offsetTop < (window.innerHeight + scrollTop)) {
bgelement.style["background-image"] = "url('" + bgelement.dataset.bgsrc + "')";
bgelement.classList.remove('lazybg');
}
});
if (lazyloadBgImages.length === 0) {
document.removeEventListener("scroll", lazyload);
window.removeEventListener("resize", lazyload);
window.removeEventListener("orientationChange", lazyload);
}
}, 20);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment