Skip to content

Instantly share code, notes, and snippets.

@joeynimu
Last active April 24, 2018 17:22
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 joeynimu/f559df14c97e3ce769dcf934a4283837 to your computer and use it in GitHub Desktop.
Save joeynimu/f559df14c97e3ce769dcf934a4283837 to your computer and use it in GitHub Desktop.
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