Projects Blog

Improve performance and user experience in images used through CSS

In this article, we’ll explore a strategy to improve the performance and user experience for a background image loaded through CSS. This will help mitigate common issues like image flickering.

Our starting point will be using an image as a background, only for decorative purposes. While this article focuses on the technical aspects, we won’t delve into the decision-making process for considering whether an image is decorative or not.

For this purpose, we’ll compare two different methods for loading images on a website: HTML and CSS.

Through HTML

When an image is included directly in HTML, it is loaded during the preload scanner phase.

In this phase, the browser will start downloading high-priority resources like CSS, JavaScript, images, and fonts.

Network request from the Chrome

You can check this behavior in the following page.

Through CSS

However, when an image is specified through CSS, such as when we use a background image, the browser loads the image after the CSS has been downloaded and parsed, which occurs after the preload scanner phase.

Network request from the Chrome

This results in slower loading times for the image and a flickering effect, as you can see in the demo page I have prepared for this article.

Preloading CSS images for improved loading performance

We can implement a strategy for enhance the resources download, in this case, images: using the link tag, using rel="preload" and as="image" attributes.

<link
rel="preload"
as="image"
href="/path/to/image.png"
/>

Doing this will advance the loading of the images to the scanner phase, so they will be available earlier and reduce the flickering effect, as you can see in the demo page.

Network request from the Chrome

I hope you found this article useful.

Happy coding! 🚀

Related posts