Skip to content

Instantly share code, notes, and snippets.

@mauricerenck
Created February 6, 2021 09:29
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 mauricerenck/80ea93a1899386c79998e7a309846376 to your computer and use it in GitHub Desktop.
Save mauricerenck/80ea93a1899386c79998e7a309846376 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(function(entries, observer) { // Loop through IntersectionObserverEntry objects entries.forEach(function(entry) { // Do these if the target intersects with the root if (entry.isIntersecting) { let lazyImage: any = entry.target lazyImage.src = lazyImage.dataset.src lazyImage.classList.remove('lazy') 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