Main objective of this post to give you the best example of How to work with SVG Sprites to Reduce Load Time
It’s an excellent way to handle images (mostly icons or similar). IMO, Its a superior way than using the icon fonts. This method also includes scaling and coloring of icons without using a different image file. But, Before I start with SVG Sprites and how to use it, I want to give a quick brief about Image Sprite & SVG.
An image sprite is a logical group of multiple images put together as a single image. Using a single image instead multiple helps reduce the number of server requests and save bandwidth. With CSS we can show needed part of the sprite. I have included a quick example.
SVG stands for Scalable Vector Graphics. Its a format of vector image based on XML. Because they are scalable and don’t lose quality like rasterized images, we can use the same image for different dimension without the need for multiple images. It is also helpful for the sites which use same icon/image in various colors.
PRO TIP SVGs are also great as a replacement of 2x sized images for the higher device-pixel-ratio.
Combining the power of Image Sprites and SVG gives us SVG Sprites. As we now know using SVG reduce the need for extra images for dimensions and color on top of that with sprites we further reduce the server request for multiple images. Let’s start with creating the SVG Sprite
Creating SVG Sprite
It is so simple that you can manually do it. Here is how you should do it.
1. Open the .svg files with any text editor one by one (I prefer Sublime Text).
2. You will see some code like below for each SVG file:
The part of the code which you should copy shape(s), path(s) or whatever inside g tag here or in some case inside symbol tag.
3. Create a file svg-sprite.svg or something similar with following code template:
Every symbol will contain the content of only one file.
id in the symbol will be used to show the icon wherever needed.
viewBox is a list of four numbers min-x, min-y, width and height which bounds the given element.
4. Use the content from your each SVG files and the final code in the file should look something like this
You can alternatively use this NPM module svg-sprite
Yay! SVG Sprite is completed now and ready to be used anywhere in your web page. Now, its time to know how to use it.
Using SVG Sprite
1. You need to put your SVG Sprite code at the top of your HTML Document. Including the example to do it in php
Remember you need to inject this code at the top of the document. Also, you can use any language you want or just copy paste the final content of your sprite file.
2. To show the icon wherever you need to use the following code:
3. Additionally, you can use the CSS to style them, change color or even size