Background Image Preloading
- Published on
- Authors
- Name
- Jerry
(Image generated by Stable Diffusion WebUI)
While working on a project last week, I encountered a requirement where certain popup modals were initially hidden when the page was first rendered. These popup modals would only become visible when a user clicked on a specific button.
However, during the initial rendering, the nature of CSS determined that display: none
would remove the element from the rendering tree. As a result, its background image, defined as background: url("/images/background.webp")
, would not be loaded until the element was set to display: block
.
This caused a momentary blank space in the popup component when the user clicked the button, negatively impacting the user experience.
To address this issue, I implemented preloading of the background image by adding <link as="image" rel="preload" href="/images/background.webp" />
.
Since the priority doesn't need to be very high, I placed this link tag at the end of the <body>
tag. If higher priority is required, you can place the link tag in the <head>
tag. Additionally, you can add the fetchpriority="high"
attribute to further elevate the priority. This is particularly useful for ensuring the prioritized loading of critical resources.