CSS images (smart optimization)

Web-applications and web-sites use a lot of small images that create a lot of HTTP requests. This is an issue, since HTTP requests are expensive (because of the way TCP/IP works). The other issue is, that some browsers refetch an image every time an image's src attribute is changed, this can mean, that a new request is made every time an on-mouse-over effect is issued.

I have solved both issues in a smart way and I share the script which makes it all possible.

The idea

The idea is to take all separated images and concat them to one image file:

Concat images

This means that only one request is made to fetch all the images.

CSS is then used to display an image (by using background y-offset):

.email_icon {
    background: transparent url(all_images.gif) 0 -48px no-repeat;
    width: 21px;
    height: 16px;
}

This idea isn't new and has been used by Yahoo and others for a few years.

The script that does the job

I have created a script that does most of the job, i.e. it:

  • concats images into one file
  • creates a CSS file where every image is given a class

This script requires:

The script is used in following way:

python css_image_concat.py <image_dir> <out_img> <out_css>

Where the arguments are:

  • image_dir is the directory of your images
  • out_img is the image that the images should be concated to
  • out_css is the output CSS file, where image classes should be put in

A concrete example:

python css_image_concat.py imgs/icons gen/cmp_images.gif gen/cmp_images.css

How to replace an image?

Say we have following image:

<img src="imgs/icons/email_icon.gif" class="fluffy" />

You would replace this image by following layer:

<div class="cmp_email_icon fluffy"></div>

Look in your output CSS file to see the concrete classes.

Download the script

Used in practice?

I use this technique in Todoist, and so far I haven't received any bug reports about missing images :)

Code · Python · Tips 14. May 2007
© Amir Salihefendic. Powered by Skeletonz.