Optimization via stringification

One way to reduce the number of HTTP requests a page requires is to group (non-content) images into sprites. An even better way is to remove these images from the server altogether; instead include them as encoded strings in your style sheet.

Instead of…

a[href="/contact/"] {
    background: url(/images/sprite.png) no-repeat 0 -30px;
}

use something like…

a[href="/contact/"] {
    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAALJJREFUeNrs1eEJgzAQBWATHKkjZAZHiCtkhKxgRnAGR+gMWSVypflRQfOeSgvlDgTxjvuSC0RTSul+EUZhhRX+bziNj0ur8tPT7OV6qEGMFJhCaNZYBA3DAKNSiyzUIs3iPEO41EgtEhbdSQtnUAo+wlmUhiWccx+4vMs3NnqmeEmpc96/norXndbc7fC28Xa0kmNwewbdPYY3fgvMjhDFm6POOUM3kf6dFFZY4a/FKsAADsZ+Lb8VFH4AAAAASUVORK5CYII=) no-repeat;
}

I threw together a Python script which converts images to encoded strings.

#stringify.py
import base64
import sys

f = open(sys.argv[1], 'rb')
s = f.read()
f.close()

try:
    altchars = sys.argv[2]
except IndexError:
    altchars = None

print base64.b64encode(s, altchars)

Usage

$ python stringify.py /path/to/image.png

Comments

Interesting idea! I'm working on an iPhone web app … so interested in limiting requests where possible.

Would love to see some benchmark's if you have anything to show the optimization.

Also interested in what load the Base64 Decode process puts on the browser … particularly since I'm working in a 'mobile' environment… If anyone has any ideas drop a comment.

Also how this compares to say GZIP HTTP compression.

Would love to see some benchmarks if you have anything to show the optimization.

I'm running on faith at this stage. ;)

Also interested in what load the Base64 Decode process puts on the browser

There's an interesting Stack Overflow thread on base64 images. Note that the discussion focuses on the pros and cons of using base64 for content images. The case is much stronger for background images declared in style sheets, since style sheets are cached by browsers.

Also how this compares to say GZIP HTTP compression.

Do both! Serve a gzipped version of your style sheet (replete with base64 background images) to capable browsers. :D

Respond