Skip to content

Instantly share code, notes, and snippets.

@JVankat
Last active October 22, 2021 17:47
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 JVankat/d7ec9c1b3e71a24e3c6036b3e2b06851 to your computer and use it in GitHub Desktop.
Save JVankat/d7ec9c1b3e71a24e3c6036b3e2b06851 to your computer and use it in GitHub Desktop.
(() => {
const rootMargin = 500;
let nodes = [].slice.call(document.querySelectorAll('.js-lazy-load'));
const loadImage = (node) => {
const src = node.dataset.src;
node.setAttribute('src', src);
};
if ('IntersectionObserver' in window) {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
loadImage(entry.target);
observer.unobserve(entry.target);
}
});
}, {
rootMargin: `${rootMargin}px`
});
nodes.forEach((node) => {
observer.observe(node);
});
} else {
let isRunning = false;
const observe = () => {
if (isRunning) return;
isRunning = true;
setTimeout(() => {
nodes.forEach((node) => {
if ((node.getBoundingClientRect().top <= (window.innerHeight + rootMargin)
&& node.getBoundingClientRect().bottom >= 0) && getComputedStyle(node).display !== 'none') {
loadImage(node);
nodes = nodes.filter((otherNode) => otherNode !== node);
}
});
if (nodes.length === 0) {
document.removeEventListener('scroll', observe);
document.removeEventListener('resize', observe);
document.removeEventListener('orientationchange', observe);
}
isRunning = false;
}, 200);
};
document.addEventListener('scroll', observe, {passive: true});
document.addEventListener('resize', observe);
document.addEventListener('orientationchange', observe);
observe();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment