← Writing Note No. 01

Engineering

Optimizing SVGs for the best frontend performance

January 2024 2 minute read Matt Cassara

With SVGs a popular choice for rendering visual assets, as opposed to images, you should optimize your SVGs and select the most appropriate method to render them in your application.

Why is this important?

Because rendering SVGs incorrectly can have a massive negative performance impact on your site. When implemented incorrectly, they can hurt the rendering performance, increase memory usage, and increase the overall size of your JS bundle.

The fastest SVG strategy is the one that keeps markup out of your JavaScript bundle unless you truly need to manipulate it at runtime.

Let's examine the five key takeaways I discovered while doing some research into this topic.

1. Always optimize your SVGs.

This is the most important takeaway. We want our SVGs to be as small as possible. We can do this by optimizing their structure and removing unnecessary data. Many times, SVGs will have unnecessary tags or grouping which contribute to the overall size.

There are great tools which can help optimize SVGs, such as Scour, which is Python based, and SVGO, which is similar but based in NodeJS.

2. Don't use SVGs as JSX.

It's anti-pattern. SVGs aren't HTML, they are XML that describes an image. It's the most expensive form of sprite sheet: costs a minimum of 3x more than other techniques, and hurts both runtime (rendering) performance and memory usage.

3. Inline SVGs are best if you have complex SVGs, or need all the bells and whistles.

Sometimes it is unavoidable, especially if you need to manipulate the contents of the SVG, transform styles, attach event handlers, etc. Make sure they are well optimized though.

4. SVG sprites are a good alternative if you have a lot of icons.

SVG sprites function like image sprites of days long gone, where we group all the SVGs into one file, and then reference them individually by their IDs.

5. Image elements with XML data URIs are a great choice for performance.

According to an analysis by CloudFour, this is by far the fastest and most consistent technique of loading SVGs. Conversion to Base64 isn't necessary — we can inline the SVG content directly into the src attribute.

Final Thoughts

Note that the above optimizations are critical for large applications, or applications with many icons. If you only have a handful of icons or a small application, the performance benefits may be negligible. That being said, we should strive to make our software as performant as possible.