CSS Sprite : method to reduce time load images.

| November 2, 2011 | 0 Comments

CSS Sprites as any other programming technique is used to solve a specific problem.

¿What is the problem?

One of our top priorities in the process to optimize web applications should be to reduce the requests to the server once the HTML has been loaded into the client browser. Each style sheet file, each Javascript file, each image… each external element, is been requested separately and thus increase the transfer and loading time.

This increase is not proporcional to the sum of the size by this external files, so the load os 10 items of 5KB is not as fast as an element of 50KB.

The external file load time can be divided into:

  • Transfer time of the own file.
  • Connection time to resource file.
  • Process time request file.
  • Response time of web server.

Moreover, in all such transfers must take consider that the information volume is composed by:

  • File.
  • Headers.
  • Cookies.

¿How can we prevent this?

Sprite

sprite example

 

 

Obviously, there are many techniques that can be applied, we will adress one: CSS Sprite. This is a technique that was used in 2D development videogames to animate characters. As you see at the left image, the sprites were only images that contains other little images inside. In our case, the solution to multiples request of images in our style sheets throught the use of large images that contains itself several smaller images.

By this way, to show different backgrounds or more icons, we will be making a single request to the server, with corresponding savings in time and charge transfer.

 

A simple example

The main mechanism of use this technique is the correct positioining of backgrounds to show only  the part of the image that we are interested. Consider a menu, where you want to show a different icon for each option. Build on an image that contains:

Imagen completa

Our HTML might look something like:

1
2
3
4
5
<ul><code>
	<li class="option1">Option 1</li>
	<li class="option2">Option 2</li>
	<li class="option3">Option 3</li>
</code></ul>

and the CSS:

1
2
3
4
5
<code>
<pre escaped="true" lang="css" line="1">.option1, .option2, .option3 { padding-left:20px; }
.option1 { background:url(iconos.png) 0 0 no-repeat;
.option2 { background:url(iconos.png) 0 -30px no-repeat;
.option3 { background:url(iconos.png) 0 -60px no-repeat;

We played with the image vertical positioning to show only that part os this that we want, which contains the icon in question:

Ejemplo uso sprites

Ejemplo uso sprites

You can do simply tests to measure load times using Firebug in FireFox or any other development tool linked to a web browser.

A major disadvantage of this technique is that it complicates the design of the images.


Source: Tutorial básico sobre CSS Sprite

 

Tags:

Category: Others

Leave a Reply