Will the browser cache the CSS background image when not in use?

If you have two rules:

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

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

Will your browser cache both or only the one that is actually displayed ( bar.gif in this case)?

Is this true in all settings? (rules in different files !important apply to one, etc.)

+7
css caching
source share
5 answers

I assume that cache is used here, you mean preload. Actual "caching" is associated with expiration of headers, etc.

It completely depends on the behavior of the browser and what it wants to do. However, my experience is that modern browsers don't bother downloading the image defined in the CSS file, unless the image is actually called up.

This is one of the reasons why some people prefer to make both the default state and the element freeze in the same image, and then use the background-position property for the change that is visible. There is a bit more overhead, but there is also no delay between the freeze and the displayed freeze state, which makes it smoother.

+3
source share

The browser does not load images when it reads css, it just takes them into account. And when he starts showing the page, he starts uploading images.

So, in your case, you already override the css rule, and when the browser displays the page, it ignores your css rule and, of course, does not load your first image.

+3
source share

The best I can say (with FireBug) is that it only pulls out the images you show, not the ones that are defined.

+1
source share

Using tail -f in 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 tried to download "bar.gif" (which was 404 not found because I did not have this image).

If you are interested in other browsers, I can also check them out.

+1
source share

if both rules have the same specificity, then they will apply. more about specificity here.

0
source share

All Articles