tags:

views:

130

answers:

5

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)

+1  A: 

Best as I can tell (with FireBug), it only pulls the images you display, not the ones defined.

joshtronic
+2  A: 

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.

Matchu
Thanks for the example of where it might matter - good to know.
Jamie Wong
A: 

if both rules has same specificity then later would be applied. read more about specificity here.

Ghost
I know which one is applied - I even state which one is displayed in the question. That's not what the question is.
Jamie Wong
only those ones which are applied, will be cached.
Ghost
+2  A: 

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.

Sinan Y.
+1  A: 

Using tail -f on my local apache log, I found the following:

::1 - - [21/Jul/2010:13:28:50 -0700] "GET /test.html HTTP/1.1" 200 127
::1 - - [21/Jul/2010:13:28:50 -0700] "GET /test.css HTTP/1.1" 304 -
::1 - - [21/Jul/2010:13:28:50 -0700] "GET /bar.gif HTTP/1.1" 404 205

Using firefox, the browser only attempted to load "bar.gif" (which was 404 not found because I didn't have that image).

If you are interested in other browsers, I could test those as well.

direct00
+1 - Good test methodology - will keep that in mind if I need to test this extensively. Thanks.
Jamie Wong