Using the data URI scheme to reduce an HTTP request

Ever wanted to include a 1px wide/high background image that repeats (one way), to your existing sprite image just to reduce that one HTTP request, even though it may not have that great an impact on speed ?

Since the image repeats itself (repeat-x or repeat-y, not both-ways), embedding it to a sprite is only useful if image’s width/height spans across the sprite image.
Using the data URI scheme, its possible to embed an image into a background-image property directly. This is supported by almost all browsers except IE7 and below. (Use this to convert an image to base64 format)

This is normally not a good solution because the base64 encoded string of the image is more (1/3 more) in bytes than the image file itself. But for small images that, say, act as a background image for a navigation container, its a good trade-off for that additional HTTP request.
And for IE6 & IE7, use the image itself.

style.css

.nav
{
    background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAiCAYAAACeLbMRAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMHw4JJ8ytHAkAAAAhSURBVAjXY2DABYyMjP4zMTAwMFCJ+Pr1K4k6GBkZkbgApdoEsBPcDsAAAAAASUVORK5CYII%3D');
}

HTML page

<!--[if lt IE 8]>
<link rel="stylesheet" type="text/css" href="ie67.css" />
<![endif]-->

ie67.css

.nav
{
    background-image:url(images/nav-bg.png);
}
Category : Performance . Tags : , .

Leave a Reply