Sunday, April 26, 2009

CSS Sprite for Performance Improvement

You may have noticed that I have 20 small images under Categories on the right side of my blog. Previously I was loading each of those from a separate image file. That (among other things) was slowing down the loading of the page. That's because the Browser has to make a separate HTTP Get request for each one, and that takes time.

To improve things, I used a technique known as CSS Sprites. I combined all the images into one image file. I then deleted the img tags I was using, and replaced them with divs. I gave each div a unique ID (e.g. id='cat3'), and then styled them as follows:

.categories_div li div {
height: 60px;
width: 50px;
background: url('images/sidebaricons.jpg') no-repeat;
float: left;
margin-right: 5px;
padding-bottom: 5px;
}

div#cat2 { background-position: 0px -85px; }
div#cat3 { background-position: 0px -170px; }
div#cat4 { background-position: 0px -255px; }
div#cat5 { background-position: 0px -340px; }
div#cat6 { background-position: 0px -425px; }
div#cat7 { background-position: 0px -510px; }
div#cat8 { background-position: 0px -595px; }
div#cat9 { background-position: 0px -680px; }
div#cat10 { background-position: 0px -765px; }
div#cat11 { background-position: 0px -850px; }
div#cat12 { background-position: 0px -935px; }
div#cat13 { background-position: 0px -1020px; }
div#cat14 { background-position: 0px -1105px; }
div#cat15 { background-position: 0px -1190px; }
div#cat16 { background-position: 0px -1275px; }
div#cat17 { background-position: 0px -1360px; }
div#cat18 { background-position: 0px -1445px; }
div#cat19 { background-position: 0px -1530px; } 
div#cat20 { background-position: 0px -1615px; } 

The key is to explicitly size the divs to match the size of the old individual images, then use the new combined image as a background for each of them. We then shift the position of the background around so that the right part of the combined background image shows through.

The net effect was no change in the look of my blog, but saving a few seconds on load time.

Note: Since writing this post, I added an additional icon to categories. For a little while I am going to load it using a regular img tag instead of incorporating it into the background image to show you the differences between image load times. It's the red mixer image at the very top; watch how that image and the rest of the icons load, you will observe a definite difference.

Post a Comment

Note: Only a member of this blog may post a comment.