Skip to content

Instantly share code, notes, and snippets.

@juanallo

juanallo/lazyLoadImages.js

Last active May 25, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.