Lazy loading offscreen images with plain JavaScript, Angular or React
I found one interesting suggestion by Lighthouse
audit on my website, it was saying:
Consider lazy-loading offscreen images to improve page load speed and time to interactive.
And a link introduced me a relatively new IntersectionObserver API with timely advice not to observe too many things to avoid performance penalty:
Intersect all the things!
No! Bad developer! That’s not mindful usage of your user’s CPU cycles. Let’s think about an infinite scroller as an example:
Quickly I tempted to try this API on my page where a bunch of images are shown. Current image count per page is under 30 but likely to grow and 5 images pagination is already in place to keep the page loading accepably fast but I felt like user experience with prev
and more
buttons wasn’t that great and also user had to wait loading 5 images to see the page where user can actually see at most 2 images in a screen.
Here I will show 3 examples of using this API — first one with plain JavaScript, second one with Angular
framework and last one with React
library.
In all examples,
- web served by
Firebase hosting
- fetch image URLs from the common REST API hosted on
cloud function
- server-side rendered by
https cloud function
- on client browser, use IntersectionObserver API to load only…