Scalable Vector Graphics (SVGs) are a great way of creating responsive images that stay crisp and sharp whatever resolution you are viewing them at. They can also be very small in size providing they have been correctly optimised for the web. You could easily write a whole article on this alone but what we’re going to look at today is embedding them in style sheets and how to do it properly so as to make them compatible across all modern browsers.

Why and what are the benefits

The main reason for embedding them in style sheets is to reduce the number of round trips the clients browser has to make to render a page. The more images you can embed in a style sheet, the fewer number of  HTTP requests the browser has to make reducing page load times. But the other benefit is that when the host server is configured to use compression such as GZIP, the file size of the CSS containing the Data URI SVGs compresses extremely well compared to using Base64 encoded type images.

Example of Embedding SVGs in CSS

To demonstrate how well this method can work, I will take a JQuery plugin (a Lightbox alternative) which I use quite a lot, Colorbox.

Firstly in its native format, Colorbox consists of a minified javascript file jquery.colorbox-min.js (11.6kb), a style sheet (4.3kb), and five .png/.gif images with total size of 10kb. When you factor in GZIP compression, you have 7 HTTP requests totalling 16kb which is not massive, but can be improved on.

If you recreate all the images as SVGs and embed them in your stylesheet, you now only have 2 HTTP requests (one .css file and the minified .js file), both of which compress down to just 6.46kb saving not just 10kb but more importantly 5 HTTP requests.

The code for the style sheet now looks like this:

To get SVGs to work across all browsers, a certain amount of reformatting of the XML code is needed. The main stumbling block is IE, but with a little tweaking even this browser will play ball. For IE, a certain amount of URI encoding is required, but fortunately not a full encode as that would increase the file size considerably. The best rule of thumbs for embedding SVGs are:

The other clever part about the CSS above, is that we have swapped out the animated 9kb loading.gif graphic for a SVG whilst maintaining IE11/Edge support. I have seen many SVG based spinner examples on the web, but none that support IE and Edge. The trick is to use a static SVG and then use a keyframe animation to rotate the image 360° infinitely

Add a comment