0

I have a page with many square images (same width and height) where size is controlled with width:50%. They will be lazy loaded with lozad.js (https://www.npmjs.com/package/lozad) that uses IntersectionObserver. The problem is that IntersectionObserver will compute all images are visibility since the height is 0 (or unknown) and all images will be loaded immediately. I'll like to set the height the same as the width but cannot see how this is possible!?

<img class="lozad" style="width:50%;" data-src="1.jpeg">
<img class="lozad" style="width:50%;" data-src="2.jpeg">
<img class="lozad" style="width:50%;" data-src="3.jpeg">
<img class="lozad" style="width:50%;" data-src="4.jpeg">
<img class="lozad" style="width:50%;" data-src="5.jpeg">
<img class="lozad" style="width:50%;" data-src="6.jpeg">
.
.
.
.
<img class="lozad" style="width:50%;" data-src="99.jpeg">
<img class="lozad" style="width:50%;" data-src="100.jpeg">
Stig
  • 1,974
  • 2
  • 23
  • 50

1 Answers1

0

I have implemented the similar page without using lozad.js. The idea was based on the assumption that you can approximate the number of images that would guarantee to cover the available screen height all the time, say INTERSECT_PAGESIZE = 2. Then your page can load only 2 images and lazyload offscreen images as user scrolls down the page by using IntersectionObserver API.

First, your page template provide additional data-idx which starts from 0:

<img data-idx="0" data-src="0.jpeg" class="image1">
<img data-idx="1" data-src="1.jpeg" class="image1">
<img data-idx="2" data-src="2.jpeg" class="image1">
...

So when the page is loaded first, no image will be loaded as src attribute hasn't been provided yet. Then pseudo code below shows what your javascript can do:

  1. query all img.image1 tags and keep it as list
  2. for each img, add load event listener that calls this.observe(img)
  3. in indexToObserve setter, for first 2 imgs from the given index, set src attribute with value from data-src
  4. set up the API so that it detects the observed element is being scrolled down then sets new indexToObserve to trigger loading 2 more images

More details explained here that provides 3 examples (with plain javascript, Angular, or React) and links to repos and demos.

bob
  • 2,674
  • 1
  • 29
  • 46