Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Images Load Faster in HTML or CSS?

If I load an image using this html on my sidebar

<img src="http://fc06.deviantart.net/fs70/f/2012/099/d/f/stackoverflow_16x16_icon_by_muntoo_stock-d4vl2v4.png" height="200px" width="200px" alt="image" />

Would it load any faster/slower than if I instead put on the sidebar where my style.css (which is called in the header) has

.image {    width: 200px;    height: 200px;    background-image: url('http://fc06.deviantart.net/fs70/f/2012/099/d/f/stackoverflow_16x16_icon_by_muntoo_stock-d4vl2v4.png');  }
<div class="image"></div>
like image 578
GreatestSwordsman Avatar asked Jul 16 '11 08:07

GreatestSwordsman


People also ask

Is it better to put images in HTML or CSS?

Summing up: if an image has meaning, in terms of your content, you should use an HTML image. If an image is purely decoration, you should use CSS background images.

What makes website images load faster?

The most common way to optimize images is to resize them. If you take a photo on a 24-megapixel camera, the image will be 6000x4000 pixels and might be 16 megabytes in size. That's about four times the size of the average website! You can dramatically reduce the file size by resizing the image.


2 Answers

This can easily be verified using Firebug (under Net), Chrome Developer Tools (under Network), Fiddler or any other HTTP sniffer you prefer.

If you put the image in CSS as background-image, the image will only get downloaded when that class is actually used and visible. If you put it in an img it'll be downloaded immediately and will block rendering even if it's invisible.

In the end they are both as fast if you are counting the speed at which the image loads per se. The real question is if the perceived performance is better as the order at which the image gets downloaded might be different depending on where you place your element.

I would worry more about the other aspects though. Having the image as a background-image means:

  • The image is not a content
  • It is not printable
  • You can use a sprite to reduce the number of HTTP requests (thus improving performance)
  • It is slower to animate background-image than img
like image 140
pixelfreak Avatar answered Sep 23 '22 04:09

pixelfreak


If you put them in the CSS file, then they will only start downloading once the CSS file itself has been downloaded. This might make the CSS approach slightly slower. Other than that, it should be the same.

like image 44
sagi Avatar answered Sep 23 '22 04:09

sagi