Cityrider49Cityrider49

Should You Base 64 Encode Images?

One trick many web performance junkies know is to Base 64 Encode images. Base 64 encoding allows a binary image to be converted to text using an encoder so that an image can be sent in-line with the HTML or CSS.

By converting a binary image to text and including it in-line with the HTML or CSS the number of calls the browser has to make to the server can be reduced. Less calls means better performance.

For example, let's say you have 20 icons you want to use on a project and you plan to call them from the style sheet. That would normally mean that the browser would need to make 20 calls to the server for each of those icons. Sure, a far future expiring header could be set so those icons are pulled from the browser cache after the initial download but that first trip would be painful. If they were baked into the CSS via Base 64 encoding then the CSS (with a far future expiring header) would be called once, saving 20 calls. That a huge performance improvement for any website.

Another plus is that by being text, it can be compressed with the rest of the HTML/CSS further improving performance.

All of this sounds great, so why isn't everybody doing this by default? First, it's an extra process within the development process that can easily go sideways if it's not automated. Automating the process isn't difficult and in a previous post I've outlined how to do it with COMPASS/SASS. Again it's another process within the development process which works contrary to rapid development.

Another point to consider is dynamic optimization. If you use a server plug-in like Google mod_pagespeed that optimizes images by platform, then converting the image to text will bypass that optimization because the image is no longer an image. The same is true if you use a service like Akamai Ion. Also, older browsers don't always support Base 64 image delivery.

So when should you use it? There are no standard guidelines but a few thoughts are:

  • Repeatedly used, highly optimized icon images defined in CSS
  • When the image has to appear on the website
  • With one page or small websites with limited graphics
  • When performance is everything (limited bandwidth)

Once you've worked with Base 64 encoded images, you'll quickly learn when they're the special sauce to improve website experiences and performance.

Comment & Older Posts »

Paul Wheeler

Paul Wheeler
Paul Wheeler is a software engineer specializing in web application architecture, design and development since 1995.