3

When a CSS declaration contains a valid background-image value, when will the image be downloaded? Are those images downloaded when the stylesheet is parsed or when the declaration is actually applied on a page?

In other words will I be downloading all the images mentioned in my stylesheet regardless of whether they will be used?

Additionally is there a specification that settles this (and if so is it respected) or is it left to the User-Agent?

Sébastien
  • 11,860
  • 11
  • 58
  • 78

2 Answers2

2

When you declare background-image in your stylesheet, the image will be downloaded straight away when the browser is parsing your stylesheet regardless of what you call that class in the document or you do not.

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
  • 2
    This seems to be not the case anymore, please see http://stackoverflow.com/questions/2396909/are-unused-css-images-downloaded I've done some testing of my own that confirmed the lazy-loading behavior described above. Current browsers only download the image when the rule matches at least one element. Same for fonts by the way. – dbader Jul 16 '14 at 17:43
  • This is totally wrong. If the parent of the element with `background-image` is hidden the image won't download. This is a consistent behaviour on pretty much every desktop and mobile browser. – AxeEffect Jul 19 '17 at 10:32
2

The browsers are every time more intelligent. New browsers detect the screen size and don't download images for mediaqueries that don't apply: mediaqueries and images download

Also I just found out that if you say #example{ background-image: "whatever.jpeg"} and the element #example is not present in the DOM then the browsers won't download that image as I read here: Are unused CSS images downloaded?

Beware of display:none; of course! Your responsive web site downloads those hidden elements' background images

Community
  • 1
  • 1
luigi7up
  • 5,779
  • 2
  • 48
  • 58