Tuesday, April 1, 2008

Why CSS's CLIP is your friend

When you get to the point on a project where page load-time becomes a concern, there is a usual play book that most of us pull out.


  1. Glob your CSS and JavaScript into as few files as possible.

  2. Pack or minify your JavaScript.

  3. Trim whitespace in your CSS.

  4. Start pre-loading images for roll-over effects.



Maybe you go so far as to lazy-load content via JavaScript. However, I will still do you one better...

Glob your static images onto one image map. Place all of your icons, or all of your tabs and their rollover counterparts into one larger image. Then, in the css of each image element, add a Clip definition to the CSS or style attribute.

What are the benefits?

In this case, the whole is less than the parts. This means smaller file size, but more importantly, it means far less packets. Each file is at least three packets on the wire. So, with lots of small files, such as a dozen or so icons, you can reduce the number of packets on the line by as much as two-thirds.

The second nicety of using clip is that mouse-overs are really smooth when you just shift the clip's rect rather than swapping out images.

There is another cool side-effect. If your site is slow loading for any reason, (i.e. client's machine is bogged) images will load in neat batches, rather than trickling in. This tends to actually make your site seem like it is less broken. Many users are more often annoyed by that one image that has not loaded, than when the whole lot is still loading. It is just distracting. Pay attention next time, I bet you will agree.

What are the pitfalls?

There are only two. First, clip: rect(); can be a pain to specify. You almost never get the math right the first time. (x,y,w,h) would have been a far better specification. Second, you need to pay close attention to what images you group together. Do not group together an image that should be jpeg with an image that should be a gif, and when grouping gifs, pay very close attention to the color pallet and make sure you are grouping like-images and not sacrificing too much picture quality.

That said, this trick is one that really should make into a lot of developers performance play books.

No comments: