CSS Sprites: What They Are, Why They’re Cool, and How To Use Them (Part 1)
You’ve heard of them, but…
Do you really understand them? The name might be a little misleading, because sprites aren’t little images like you might be picturing, a sprite is actually one big image. Have you ever seen the CSS technique where the “on” and “off” states of a button are contained within the same image and are activated by shifting the background-position?
Here is an example of that on CSS-Tricks.
Think of CSS Sprites as an extension of that technique. The difference is that instead of just two or three images being combined into one, you can combine an unlimited number of images into one. The origin of the term “sprites” comes from old school computer graphics and the video game industry. The idea was that the computer could fetch a graphic into memory, and then only display parts of that image at a time, which was faster than having to continually fetch new images. The sprite was the big combined graphic. CSS Sprites is pretty much the exact same theory: get the image once, shift it around and only display parts of it, saves the overhead of having to fetch multiple images.
Why combine all those images? Isn’t it quicker to have smaller images?
Nope, it’s not. Back in the day, everybody and their brothers were “slicing” images to make pages load faster. All that technique did was fool the eye to make it look like the page was loading faster by loading bits and pieces all over at once. Each one of those images is a separate HTTP-Request, and the more of those, the less efficient your page is.
Let’s look at a quote from the article “Performance Research, Part 1: What the 80/20 Rule Tells Us about Reducing HTTP Requests” by Tenni Theurer on the Yahoo! User Interface Blog.
Table 1 shows popular web sites spending between 5% and 38% of the time downloading the HTML document. The other 62% to 95% of the time is spent making HTTP requests to fetch all the components in that HTML document (i.e. images, scripts, and stylesheets). The impact of having many components in the page is exacerbated by the fact that browsers download only two or four components in parallel per hostname, depending on the HTTP version of the response and the user’s browser. Our experience shows that reducing the number of HTTP requests has the biggest impact on reducing response time and is often the easiest performance improvement to make.
|Time Retrieving HTML||Time Elsewhere|
Every single image, whether it’s an <img> tag or an background-image from your CSS is a separate HTTP-Request, so you can image how quickly those requests can wrack up.