Skip to content

Instantly share code, notes, and snippets.

@juanallo
Last active May 25, 2020 00:14
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 juanallo/9420b04973440742ab68d1fbd574aaf7 to your computer and use it in GitHub Desktop.
Save juanallo/9420b04973440742ab68d1fbd574aaf7 to your computer and use it in GitHub Desktop.
Lazy load images with IntersectionObserver
if(window.IntersectionObserver){
const observe = function (entries, observer) {
entries.forEach(function(entry) {
if(entry.isIntersecting) {
const img = entry.target
const src = img.dataset.src
const srcset = img.dataset.srcset
requestIdleCallback(function () {
if(srcset) {
img.srcset = srcset
}
img.src = src
})
observer.unobserve(img)
}
})
}
const observer = new IntersectionObserver(observe, {})
const images = document.querySelectorAll('img.lazy')
images.forEach(function(img) {
observer.observe(img)
})
}
else {
const images = document.querySelectorAll('img.lazy')
for(let i=0 ; i < images.length; i++){
const img = images[i]
const src = img.dataset.src
const srcset = img.dataset.srcset
if(srcset) {
img.srcset = srcset
}
img.src = src
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment