How can I lazy-load images with Cloudinary and Strapi?

Viewed 207

I am working on a project using Gatsby, Strapi and Cloudinary. I am deploying the frontend on Netlify and the Strapi app on Heroku (with the addition of a Postgresql database instance).

I have been searching for weeks now and but I cannot seem to find a way to lazy-load images sourced through Cloudinary.

I have replaced the default rich content editor on Strapi with the ckeditor so editors can add photos to their content. These are automatically uploaded and served by Cloudinary.

My question is, is there a way to lazy-load the images, and if so, should this be done when serving them from Cloudinary, should I do this as a Strapi middleware or simply through Gatsby?

Note: I am not sourcing the images anywhere on the front-end since it's parsed as html from Strapi. All I'm currently doing in passing the fetched content to a div using dangerouslySetInnerHtml.

1 Answers

With dangerouslySetInnerHtml directive you are inserting whatever is inside your rich text as HTML content so you lose control of customizing the behavior of that content. Hence, it will be rendered all at once.

There's no built-in way of doing this except by parsing your rich text with a third-party dependency (which I haven't been able to find)/custom method that will give you the capability of wrapping your images with any custom component. The idea, either way, is to parse your rich text blocks to customize the output.

In addition, check if the images tag (<img>) comes with the loading=lazy property attached:

<img src="image.jpg" alt="..." loading="lazy">
Related