ux icon indicating copy to clipboard operation
ux copied to clipboard

[LazyImage] Feature Proposal - lazy load with intersection observer

Open phtmgt opened this issue 4 years ago • 1 comments

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?

phtmgt avatar Dec 17 '21 09:12 phtmgt

It's easier to just use a library like lazysizes (no IO) or vanilla-lazyload if you want to have that kind of flexibility.

ToshY avatar Jun 10 '22 12:06 ToshY

Lazy loading should be enough to not load images that are outside the viewport.

Kocal avatar Apr 20 '24 06:04 Kocal

I agree with @Kocal , browsers have the best implementation you could use for this kind of feature, i would not recommand any custom code

smnandre avatar Apr 20 '24 13:04 smnandre