Created
March 23, 2020 13:41
-
-
Save 0632347878/2cbeadd4962f3b0fc521adbfb010f28c to your computer and use it in GitHub Desktop.
IntersectionObserver
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
/** | |
* For accept the lazy loading to images you need just add | |
* [data-lazy-src] with a path on image. | |
*/ | |
export default (window.onload = () => { | |
const images = document.querySelectorAll('[data-lazy-src]'); | |
if ('IntersectionObserver' in window) { | |
let observer = new IntersectionObserver( | |
(entries, observer) => { | |
entries.forEach(entry => { | |
if (!entry.isIntersecting) return; | |
const lazyLink = entry.target.dataset.lazySrc; | |
const closestLink = entry.target.closest('a'); | |
closestLink ? closestLink.classList.add('h-blur-up', 'lazyload') : null; | |
entry.target.tagName === 'SOURCE' ? entry.target.srcset = lazyLink : entry.target.src = lazyLink; | |
observer.unobserve(entry.target); | |
}); | |
}, {rootMargin: "0px 0px -100px 0px"} | |
); | |
images.forEach(img => observer.observe(img)); | |
} else images.forEach(img => { | |
img.tagName === 'SOURCE' ? img.srcset = img.dataset.lazySrc : img.src = img.dataset.lazySrc; | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment