Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the browser cache a CSS background image if it's not used?

Tags:

css

caching

When you have two rules like this:

.foo {
  background-image: url(foo.gif);
}

.foo {
  background-image: url(bar.gif);
}

and have <div class='foo'>Foobar</div>

Will your browser cache both, or just the one actually getting displayed (bar.gif in this case)?

Is this true in all setups? (the rules being in different files, !important being applied to one, etc)

like image 772
Jamie Wong Avatar asked Jul 21 '10 20:07

Jamie Wong


2 Answers

I assume by "cache" here, you mean "preload". Actual "caching" has to do with expires headers and the like.

It's entirely based on the browser's behavior and what it chooses to do. However, my experience is that modern browsers don't bother to load an image defined in a CSS file unless the image is actually called for.

This is one reason that some choose to make both the default and hover state of an element into one image, and then use the background-position property to change which is visible. There's a bit more overhead, but there is also no delay between hover and the hover state being displayed, making for a smoother experience.

like image 85
Matchu Avatar answered Sep 21 '22 14:09

Matchu


Browser doesn't load the images when it reads the css, it just keeps them in mind. And when it starts rendering the page it starts to load images.

So in your case you already override your css rule, and when browser renders the page it ignores your css rule and naturally it doesn't load your first image.

like image 42
Sinan Avatar answered Sep 18 '22 14:09

Sinan