[LazyImage] Feature Proposal - lazy load with intersection observer
This is the natural next step. Google's PageSpeed insights does not like it when you're loading offscreen images w/out need and it actually makes sense.
Came upon this code, which looks quite efficient:
let images = [...document.querySelectorAll('.lazy-image')]
const interactSettings = {
root: document.querySelector('.center'),
rootMargin: '0px 0px 200px 0px'
}
function onIntersection(imageEntites) {
imageEntites.forEach(image => {
if (image.isIntersecting) {
observer.unobserve(image.target)
image.target.src = image.target.dataset.src
image.target.onload = () => image.target.classList.add('loaded')
}
})
}
let observer = new IntersectionObserver(onIntersection, interactSettings)
images.forEach(image => observer.observe(image))
What do you think? Maybe allowing choice between loading upon completion of initial load or using intersection observer?
It's easier to just use a library like lazysizes (no IO) or vanilla-lazyload if you want to have that kind of flexibility.
Lazy loading should be enough to not load images that are outside the viewport.
I agree with @Kocal , browsers have the best implementation you could use for this kind of feature, i would not recommand any custom code