开发者

Inline base64-encoded images or HTTP request?

There are at least two ways to use an image in CSS:

  • with an HTTP request;

    url(/path/to/image.png)

  • with a data URL.

    开发者_开发技巧

    url(data:image/png;base64,BASE64_ENCODED_DATA_HERE)

But I was wondering, as base64-encoded data takes 33% more space, therefore 33% more time to load, is it worth it, or should I just make an HTTP request--using a sprite if there're several images?


A separate request is almost always preferable because with data: URIs,

  • it doesn't work in older IEs and is limited to 32k in IE8

  • it can be argued that it goes against separation of styling and content

  • Style sheet files get blown up, which may cause trouble if the browser's developers never expected CSS files to reach these kinds of sizes

I would use it only when there is no other choice.


The web server should take care of the 33 % more space by GZIP-ing all text files so that should not be that big of a problem. This together with reducing the number of HTTP requests (which is very important performance-wise) makes the method worthwhile. Also, the images are still cached but now in the CSS file instead of in separate files.

Preferably the embedding should be done with a build script that inserts the data URIs. That way we don't have to care about large chunks of base64-encoded data when editing the CSS files. Also, remember to have a good solution if images occur more than one time in the file, e.g. re-writing the CSS rules. We don't want the file to be larger than necessary.

There are problems with IE though. IE<=7 can't handle data URIs at all and IE8 can't handle them for larger URIs than 32K. The latter could be solved by simply not embedding too large images (maybe you shouldn't anyway). Regarding IE<=7 the problem can be solved by using MHTML instead and specifying different CSS files for different browsers using IE conditional comments.

Here is a good blog post about embedding images in CSS and how to fix the problems for IE: http://blog.meebo.com/?p=2320


Personally, I would always go with a separate request. I've had trouble in the past with Internet Explorer and data:url images.

It seems IE8 limits url length to 32KB, which is often not enough for images.

Wikipedia on Browser Support

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜