In almost all the web application, we use many icons to make our pages look elegant. This might be good for the UI/UX but it has a huge implication on the network performance.
Consider a page which shows 45 various services provided by an organization. There will be 45 network calls required to get all the icons. Each browser opens a certain maximum number of connections in parallel to optimize its performance (Chrome opens max 6 connections at a time).
One way of getting all the images at once is to use domain sharding, in our case we need 45/6 = 8 (rounded off) different domains to serve all the icons at once.
Another and the popular way of achieving it is by using Sprite Images. It’s a single image which contains all the icons in it. CSS can be used to display all the icons at their respective places in the web page.
The following link has 33 icons which are served through a single Sprite image.
This is the sprite image used
How to create and use Sprites:
There are a lot of CLI/GUI tools to generate the sprite image. The above image has been used using Python-based CLI tool called Glue.
Just pass the directory of icons and it will generate a PNG image with all the icons and a CSS file with all the image names as classes. Use these classes in HTML where ever you want to show the icons. The sprite image and CSS file can be customized in several ways as required by the developers. Please refer its documentation for all possible options.
Example usage of the tool :
glue-sprite icons/ –img=assets/images/ –css=. –sprite-namespace= –namespace= –force
Explanation of the command:
icons/ – directory with all the icons
–img = assets/images/ – the sprite image will be created under this path (this path is used so that generated CSS classes also get the assets/images path – standard path for serving images through rails).
–css = . CSS file will be created in the current directory.
–sprite-namespace = to append anything in class name
–namespace= to prepend anything in class name
–force – not to cache while creating sprite.
A sample of CSS file generated:
Below is the sample HTML snippet to use the above icons:
<div> <span class="wi_fi_zone"> WiFi facilities </span> <span class="blood_bank"> Blood bank available </span> </div>