开发者

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

开发者 https://www.devze.com 2023-01-08 13:01 出处:网络
When you have two rules like this: .foo { backgro开发者_开发知识库und-image: url(foo.gif); } .foo {

When you have two rules like this:

.foo {
  backgro开发者_开发知识库und-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)


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.


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.


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号