Skip to content

Instantly share code, notes, and snippets.

@joeynimu
Last active Apr 24, 2018
Embed
What would you like to do?
LazyLoadImages
const lazyLoad = () => () => {
// create an array from <img /> tags with a .lazy class
const lazyImages = Array.from(document.querySelectorAll('img.lazy'))
if ('IntersectionObserver' in window && 'IntersectionObserverEntry' in window && 'intersectionRatio' in window.IntersectionObserverEntry.prototype) {
let lazyImageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
let lazyImage = entry.target
lazyImage.src = lazyImage.dataset.src
lazyImage.srcset = lazyImage.dataset.srcset
lazyImage.classList.remove('lazy')
lazyImageObserver.unobserve(lazyImage)
}
})
})
lazyImages.forEach(lazyImage => {
lazyImageObserver.observe(lazyImage)
})
} else {
//have a defaulf placeholder
}
}
document.addEventListener('DOMContentLoaded', lazyLoad)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment