14

I use CSS to place a lot of my images (as backgrounds for <div>) and I often find that they load very slowly this way. They seem to be the last thing to load. Even small little icon images take a while to show up this way. Is there a way to tell the browser a priority for images? Or get it to download the images in the CSS file earlier and render them earlier?

1
  • The CSS sprites answer to your other question will probably help solve this one too. Aug 16, 2010 at 12:13

6 Answers 6

10

CSS is for styling, not content. Browsers (rightly) try and display content before adding styling, hence the reason why images in style-sheets are usually downloaded last. If images are important to your content then add them via standard HTML <IMG> tags.

2
  • 2
    Great advice, particularly the last sentence. Image for decoration: CSS; Images for content: HTML. Aug 16, 2010 at 15:19
  • 1
    Daniel's description of the images he's referring to ("backgrounds", "icons") makes them sound very much like decoration, as opposed to content. I think they're right to be in the CSS.
    – Bobby Jack
    Aug 17, 2010 at 17:07
5

Use absolute URI's from your stylesheet and add the images from IMG tags to a hidden <div> on the page (this assumes you're using the same images on every page; ideally in the footer so they're all loaded and cached on any given page call).

Images on the page get priority and, once the images are cached, they'll render immediately on subsequent page requests.

2

For browsers that support the data URI type (see http://en.wikipedia.org/wiki/Data_Uri for info) to include the image in the CSS itself.

This has a few disadvantages though:

  • The data is reloaded when the CSS is, rather than being separately cached, though unless your CSS changes regularly this is not much of a problem.
  • CSS's lack of inheritance and such means there may be times (wasting bandwidth) when you have to include the same graphic multiple times or alter the classes used in your document.
  • The images are base64 encoded when used this way which means they take more bandwidth (though the bandwidth issue is much less significant if you are sending the data compressed).
  • You'll need to provide alternate styles for browsers that do not support the data URIs, some of which are far from uncommon (IE6 and IE7 for instance).
1

As of right now there is no way to specify which files download first. FYI, images specified in CSS files as background images download last probably because the browser sees them non-content and thus a lower priority so avoid using them for important images that you want to load quickly.

1

Use CSS sprites, especially for icons.

1

Make your images as small as possible. You can use smush.it to remove unnecessary bytes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.