Skip to content

Instantly share code, notes, and snippets.

@davidhellmann
Forked from mauricerenck/lazy.ts
Last active February 6, 2021 10:02
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 davidhellmann/e988847972afd4c5cf015ef9eef2558b to your computer and use it in GitHub Desktop.
Save davidhellmann/e988847972afd4c5cf015ef9eef2558b to your computer and use it in GitHub Desktop.
export const initLazyloading = (selector: string): void => {
let images = document.querySelectorAll(selector);
if ('IntersectionObserver' in window) {
// Create new observer object
let lazyImageObserver = new IntersectionObserver((entries, observer) => {
// Loop through IntersectionObserverEntry objects
entries.forEach((entry) => {
// Do these if the target intersects with the root
if (entry.isIntersecting) {
let lazyImage: any = entry.target;
if (lazyImage.nodeName === 'IMG') {
lazyImage.src = lazyImage.dataset.src || lazyImage.src;
lazyImage.srcset = lazyImage.dataset.srcset;
lazyImage.sizes = `${lazyImage.getBoundingClientRect().width}px`;
}
if (lazyImage.nodeName === 'SOURCE') {
lazyImage.srcset = lazyImage.dataset.srcset;
}
lazyImage.classList.remove('lazyload');
lazyImage.classList.add('lazyloaded');
lazyImageObserver.unobserve(lazyImage);
}
});
});
// Loop through and observe each image
images.forEach(function(lazyImage) {
lazyImageObserver.observe(lazyImage);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment