-
-
Save JVankat/d7ec9c1b3e71a24e3c6036b3e2b06851 to your computer and use it in GitHub Desktop.
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
(() => { | |
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