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"undefined" anchor link
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.

You can check this behavior in the following page.
Through CSS"undefined" anchor link
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.

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"undefined" anchor link
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.

I hope you found this article useful.
Happy coding! 🚀