-
-
Save davidhellmann/e988847972afd4c5cf015ef9eef2558b to your computer and use it in GitHub Desktop.
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
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