Data URIs are one of the best techniques in CSS, allowing developers to avoid referencing external images and instead embed them directly into a stylesheet. The main advantage of this approach is to save HTTP requests.
HTTP requests are a huge performance bottleneck, and the reason techniques such as CSS image sprites have been popular for some time. Basically, if you can avoid requesting an extra file, not only does it save your server the work of looking up the file, but it also saves your user the download time. In fact, HTTP request management is so important, that it is the top issue in the Yahoo Performance Rules.
Data URIs are an excellent way to reduce HTTP requests and speed up your pages, so let’s walk through how to use them in all major browsers.
When To Use Data URIs
When used instead of an image sprite, data URIs save a single HTTP request, and every little bit counts. However they are even more useful for images that are difficult to include in sprite sheets, for instance custom list bullets that need a varying amount of whitespace.
Although data URIs are an excellent way to reduce HTTP requests, it doesn’t make sense to use them in every situation. Since they embed the raw file data directly in the stylesheet, data URIs can lead to stylesheet bloat if they are used heavy-handedly.
Data URIs are great for any imagery that is repeated on all the pages of your site. However, for page-specific images it is usually better to reference an external image in the stylesheet. Since the file data is embedded directly in the stylesheet, data URIs will be downloaded by all your site’s visitors, regardless of whether they hit the page with that particular image. That said, you can feel free to embed page-specific data URIs on the individual page, just take care not to include them in a site-wide stylesheet.
How To Use Data URIs
Fortunately embedding data URIs is relatively simple. First you’ll need to generate a text string of the raw image data. For this I like to use the Base64 Online Generator.
Once you have the image data, simply place it directly in your stylesheet as an inline background image:
Here we’ve used image/png to specify the content type, but make sure to change this to image/jpg or image/gif depending on the MIME type of the image you’re embedding. Additionally make sure to keep the data URI all on one line without line-breaks.
Supporting Data URIs in IE
Firefox, Chrome, Safari and Opera all support data URIs. However, as you may have guessed data URIs are not fully supported in IE, so special accommodations need to be made for everyone’s favorite browser.
Data URIs in IE8
IE8 mostly supports data URIs with a few minor caveats. The main problem is that IE8 data URIs cannot exceed 32kb, however this is not a huge issue, since embedded images rarely exceed this limit.
Additionally, data URIs can only be used for a handful of HTML elements in IE8:
No comments:
Post a Comment