I am using CSS custom properties to set the background image for a div. The div is nested inside an anchor tag to represent a clickable "card" that routes to another page.
In Chrome with dev tools open and cache disabled, when I click on the card, the background image flickers. It appears to be fetching the image again every time the state of the anchor tag changes.
Additionally, if I add text-decoration to the anchor tag on hover the image flickers when hovering too.
CSS looks like:
:root {
--image-url: url("https://images.unsplash.com/photo-1529778873920-4da4926a72c2?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80")
}
.image-div {
height: 100px;
width: 100px;
background-image: var(--image-url);
background-position: 0;
background-size: cover;
}
See the pen: https://codepen.io/hally9k/pen/RmepVe
I have found that I can stifle this flickering (and refetching) by ensuring the image is returned with a Cache-Control
header. Some common services (e.g. S3) don't return Cache-Control
headers by default.
In my humble opinion, there's an underlying browser problem that causes it to sometimes refetch images when you're using a CSS custom variable and it repaints the element. In our case this occurred only when transitioning the element. The Cache-Control
header taps into more low-level browser functionality related to resource caching.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With