And Finally
And Finally

Reputation: 5704

Many instances of one image on a page - does CSS background image perform better?

If I have to show one image many times on my HTML page, which is better from the point of view of site performance, many image tags with the same src URL, or many elements with the same background image defined in CSS? The first way, the browser should cache the image the first time it requests it, but there are still many requests to deal with. The second way, it seems to me there is just one request, when the CSS is parsed. Am I right in thinking that is more efficient?

Upvotes: 0

Views: 437

Answers (1)

Chris
Chris

Reputation: 4671

Even in the case of CSS, the multiple background-image rules would still involve the browser making one web request & then caching the image. Exactly the same mechanics would be in place. The fact that the images are referenced in CSS rather than in HTML doesn't allow the browser to magically 'know' it already has the image without even checking the cache.

The primary difference between your two scenarios is that if you reference all the images in CSS, the CSS itself could be cached, which would represent a minor performance improvement, and your HTML files will be smaller. The improvement may or may not be substantial - it depends on many other factors such as how many image references we're actually talking about, whether your HTML files themselves are cacheable, how many page-views your users make on average, and so on.

All said, the CSS background-image is likely to be marginally better, but not for the reason you state. Whether you're talking HTML or CSS, you're still looking at one request followed by a bunch of cache-hits.

Upvotes: 1

Related Questions