const fetchImage = url => {
return new Promise((resolve, reject) => {
const image = new Image()
image.src = url
image.onload = resolve
image.onerror = reject
})
}
const loadImage = image => {
const src = image.dataset.src
fetchImage(src).then(() => {
image.src = src
})
}
const handleIntersection = (entries, observer) => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
setTimeout(() => {
loadImage(entry.target)
}, 1000)
}
})
}
const options = {
rootMargin: '0px',
threshold: 0.1
}
const observer = new IntersectionObserver(handleIntersection, options)
const images = document.querySelectorAll('img')
images.forEach(img => {
observer.observe(img)
})