The other day in the team we were playing with one simple bug.
The bug was why the Intersection Observer is loading almost all images on the page which are not in the viewport?
It was simple, the src attribute was empty:
<img src="" data-src="" class="lazy-load" alt="Some title" />
This was making all images on the page to render close one to another with the size of the defined line-height. So almost all images were initially in the viewport when the Intersection Observer was triggered.
Ok, we got the issue, so let's define some dimensions to the img tags:
<img src="" data-src="https://URL_TO_IMAGE" class="lazy-load" height="200" width="200" alt="Some title" />
Ahh, still the images are only with the size of the line-height and still almost all are visible...
Then after adding some CSS to try to set the size "min-height" and etc. we were not able to set the proper dimensions.
Suddenly someone remembers it if you don't have some URL to image in the src attribute, the Width and Height won't be used and the tag won't be that size.
The simple solution was:
<img src="https://URL_TO_1x1_PIXEL_IMAGE" data-src="https://URL_TO_REAL_IMAGE" class="lazy-load" height="200" width="200" alt="Some title" />
Yes, if you set 1x1 image in the src, the height and width will be applied and the Intersection Observer will do his job properly.
Most of the articles for Image lazy loading are not mentioning that you need src attribute filled, it is better for UI and for the lazy load.
Top comments (0)