DEV Community

Cover image for Fixing lazyload images with React Server-Side Render
Hieu Nguyen
Hieu Nguyen

Posted on • Updated on

Fixing lazyload images with React Server-Side Render

I've recently realized my server render pages has a problem. The offscreen lazyload image don't show up.

In case you don't know, offscreen images won't load until it shows up onscreen. It helps to reduce unecessery loading to improve performance.

As usual, I impletemented image lazy loading by (1) get all img elements, (2) move photo URL to data-src, and remove src. Then (3) observe whenever each of them scrolled onscreen, move the photo URL back to src to load.

It works when React running on the client-side. But when render on the server-side, the images don't show up.

Turn out, it's a little different. As usual, the server will return a hydrated React page. Then the client will re-render the page again as a normal React page.

The problem was, the lazyload function executed twice as well. The first time, src is a link, and set to empty after assigning the link to data-src. Then the second time, src was empty, and that empty value is again, assigned to data-src. And when users viewing the page, it will start to load an empty value.

I fixed this problem by checking if src is not empty, before moving it to data-src.

In case you're looking for the code, here is a basic lazyImages.ts with some favors (add loading class, check for offscreen images)

You can use the lazyImages as following:

lazyImages();

// offset before the image is scrolled into view
lazyImages({ rootMargin: "100px" });
Enter fullscreen mode Exit fullscreen mode

Posted on Fixing lazyload images with React Server-Side Render

Top comments (2)

Collapse
 
dalbir profile image
Dalvir • Edited

How I can use this in My React Application, example please. And also please correct the type in lazyImages

Collapse
 
hieussr profile image
Hieu Nguyen

To use the function, you will need to call lazyImages as following:

lazyImages();

// offset before the image is scrolled into view
lazyImages({ rootMargin: "100px" });
Enter fullscreen mode Exit fullscreen mode

Thanks for mentioning, I've added this to the post.

Besides, what type was incorrect?