HostingGreen web hosting packages
TutorialsBeginners guides to SEO & hosting
Beginners guide to Web Hosting
create an image sprite
Back in the third section making fewer DNS and HTTP requests we talked about combining CSS and Script files. This can also be done with images using a technique called “sprites”.
What is an image sprite? - A sprite is a collection of images all put together as one image and, thus, one file. If we pool all the images of a website into one image this means that only one http request will be made for many images on a page. Yes the one image will be much bigger… but remember that the http requests normally take more time than the downloading itself? Then this is how to use this to your advantage. In addition, remember that we can force the browser to cache content discussed in the forth section: making browsers cache your page content? We can make the browser cache the one image which can contain all the images on your website.
Now for the bad part… this can be a real pain to set up, especially if you already have a site created. For a new site it is not quite so bad. The method I use is as follows:
- Put images into css backgrounds – For each image that you wish to add to the sprite, make a style with a background image of the image and replace the html with a div or span and give it the class of the style.
- Make a big image of the small images – Take each image and add them to a big image. For optimum size, try to make the big image as square as possible. I find that by adding the largest images first and then filling in the gaps with the smaller images you can usually make it fairly square.
- Make a sprite image class – Make a CSS class with the background image set to the big image that you have just created.
- Alter the CSS image classes – For each of the classes that you created in CSS, remove the background image and add a background-position, width and height. The width and height are the dimensions of the image and the background position is the coordinates in pixels for the top left corner of the required image within the big image.
Here’s an example:
background-position: -0px -223px;
… and in the html, to display the image…
<div class=”webdevelopment whimage”></div>
As I say, it can be a real pain but it can really speed up the website dramatically which will get you more visitors.
Now, to get the image cached in the browser, put a date on the end of the big image file name, change the big image class to that file name (now can you see why we put the image reference in a class of its own?) and change the .htaccess to cache images of that image type. One little trick- if you do not want to sprite all of your images (and do not want the browser to cache all of your images) you can use an extension like .jpeg for the big image, add just jpeg to the .htaccess file and use .jpg for all of your non-caching images.
Next section: Speed analysis tools and resources
Index of all our tutorials: Wight Hat tutorials