Skip to content

Instantly share code, notes, and snippets.

@mauricerenck
Created February 6, 2021 09:31
Show Gist options
  • Save mauricerenck/d6fdafdf20ed2049006f0152c292d352 to your computer and use it in GitHub Desktop.
Save mauricerenck/d6fdafdf20ed2049006f0152c292d352 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