Somewhat unusually, there’s a way of placing images on web pages without referencing an image file directly. By encoding the image information as a string of characters and numbers and placing this code in the CSS or HTML of your web pages, we can significantly decrease page load times. While this isn’t practical for large images, or any picture that might undergo frequent changes, encoding an image in the dataURI scheme can provide two significant advantages:
- Reduced HTTP Requests. Every separate file a browser has to fetch increases page load time. Merging files – whether by using sprite images or encoding them with the technique I demonstrate in this article – increases the efficiency of a page.
- Latency is the pause between a browser’s request for a file and its delivery. Latency is particularly prevalent for mobile devices; joining files together eliminates multiple, staggered delays that work to slow page load speeds.
Encoding an image is not something you can do by hand – you need to use a tool or service. A few examples:
I’ll use the PNG image shown in the top right corner of this article as an example. Encoding it as base 64 produces the following code, truncated here for brevity:
iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAA…
Now that we have the code, we can use it anywhere in our stylesheet that you can reference an image, so long as the code is prefaced with data:image/(format);base64,
header {
background-repeat: no-repeat;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAA… );
}
You can also place dataURI information in an HTML file to display an image:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA…" >
Once you do so, you can (and should) style and provide attributes to the element as you would any other : <img>
tag:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA…"
alt="Lion" style="float: right; margin-left: 2em">
Encoding image content as data is useful in many circumstances, particularly with small, repeated decorative images that would otherwise be downloaded as seperate files and add latency to your page. Background images in horizontal rules are one good example, as we shall see in the next article.
Generally speaking the greatest gains from encoding your images will be through placing the base64 code in the CSS as background-images for elements that appear on multiple pages. Such information will be cached and used throughout the site, further speeding page load times.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.