Figure 9-15. Caching an inline image with CSS

Chapter 9 - Advanced Web Performance Optimization

Embedded in XHTML files, data URI images are not cached for repeated use, nor are they cached from page to page. One technique to enable caching is to embed background images in external CSS files. CSS is cached by browsers, and these images can be reused with a selector. For example:

ul {list-style:none;}
    ul > li {
    margin:0 0 .1em;
    background:url(data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/
f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///
yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORC
MxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7) top left no-repeat;
    )
    height:14px;
    text-indent:1.5em;
}
</style>

Now the folder image is repeated for each instance of the li (or you could use a class or ID here as well):

<ul>
    <li>Testing one</li>
    <li>Two</li>
    <li>Three</li>
</ul>

Figure 9-15 shows results in the page in Firefox.

dhtml news flipper webreference.com

Figure 9-15. Caching an inline image with CSS

And the live example below:

There is one issue with this approach. You must recalculate the Base64 data and edit the CSS file every time the image changes. The problem has a simple PHP solution:

<?php echo base64_encode(file_get_contents(" ../images/folder16.gif")) ?>

This code reads the image and converts it to Base64 automatically at the server. You pay for this editing convenience with some server-side processing.