Skip to content

Instantly share code, notes, and snippets.

@0632347878
Created March 23, 2020 13:41
Show Gist options
  • Save 0632347878/2cbeadd4962f3b0fc521adbfb010f28c to your computer and use it in GitHub Desktop.
Save 0632347878/2cbeadd4962f3b0fc521adbfb010f28c to your computer and use it in GitHub Desktop.
IntersectionObserver
/**
* 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