Encode Small Images in Stylesheets

Continuing the earlier theme of Optimizing Images to Save Bandwidth and Speed Page Load, you can also encode small (background) images directly in your stylesheets. For each image / page element encoded within a stylesheet, it means one less HTTP connection for content, which in turn means pages finish loading faster. These images should generally be small and downloadable quickly — what you want to save is the HTTP connection overhead, not the download time (both images and stylesheets are generally cached after downloading). The images should also be encoded within sourced stylesheet files, so the stylesheet files can be cached by the browser. If you encode images within your content (using <style></style> tags for example), the encoded image will have to be downloaded for every page view, so although you’re saving HTTP connections, your page size has increased. By encoding images in sourced stylesheet files instead, the browser (and content delivery services) can cache the whole stylesheet, including the encoded image(s).

In these days of themes and plugins, that often come with their own stylesheets and images, it can be difficult to track down every image that can / should be encoded. A quick way to determine which images can be encoded is to use a website speed testing tool like webpagetest.org, or one of many others that offer a waterfall chart. The chart is important — you need to locate the small image elements that are downloaded quickly.

For example, one of the themes I use (on another website), includes the following CSS stylesheet element:

The bullets.png file is only 302 bytes, which makes it the perfect for candidate for encoding within a stylesheet. The encoded version looks like this:

If you have access to a UNIX shell, you can generate base64 encoded strings using the base64 command. For example:

Alternatively you can also use an online base64 image encoder like this one, where you upload your image and the website returns the complete CSS stylesheet code.

Find this content useful? Share it with your friends!