Optimize Your Web Page with CSS Sprites | WebReference | WebReference

Optimize Your Web Page with CSS Sprites | WebReference

By Arpan Dhandhania


How do you optimize a Web page? The answer to this question is neither unique nor simple. Different methods are used for different types of content. If your website contains dynamic content that is pulled from a database, then you should consider caching methods where the HTML version of a page is stored temporarily until the content changes. If your website contains videos, then you could upload the video to a streaming service such as YouTube or Vimeo and let your users stream the video off their server. Since this is their primary business, you can be assured that they would have optimized their servers to serve videos as fast as possible.

The two types of content that are common to all websites are text and images. Typically text is extremely lightweight and other than stripping the whitespace, there isn't much optimization that you can do with it. So that leaves us with images.

A few years ago, the trend was to slice up the design into small images and load each of them independently. All this technique did was fool the untrained eye to make it look like the page was loading faster. Though the perceived response time is quicker, in reality it takes longer to load the page. To understand this, we need to understand how the browser works.

When the user keys in a URL into the browser, a request is sent to the server asking for that resource (in this case an HTML page). The server responds with the HTML of the page. The browser then parses the HTML and for each resource in it (stylesheets, scripts, images, etc.), the browser makes a separate request to the server. Most browsers can download only up to 4 or 5 components in parallel from one host.

How Can Using CSS Sprites Optimize a Web page?

Before we get into CSS sprites, what are sprites? Spriting is an age-old technique. In the early days of video games, when memory and speed were at a premium, in order to overcome system limitations, video game producers would lay out the all the small graphics used to create the game into a grid and then display each "sprite" as needed, masking out all but the needed part of the larger image.

As they say, old habits die hard. Web programmers decided to use this optimizing technique while building webpages too. Imagine if you could mash up all the images used on a page into one large image and display only the part that contains the image wherever required. Wouldn't that drastically reduce the load time of the page? Well, that is exactly what CSS sprites are. A simple concept, which is equally simple to implement.