Optimize SVG images for the Web
Scalable Vector Graphics (SVG) images are the bee's knees, that cat's meow. For those unfamiliar with those idioms, what I mean to say is that I love to use SVG images whenever possible.
There are a few reasons why SVGs are great:
- They can be scaled up and down without distortion.
- Vector graphics are usually smaller in file size.
- The ability to use animations and transitions on layers.
As you develop your web application, the SVG files are usually exported from programs like Sketch or Adobe Illustrator. On the other hand, you could also be using icons from websites like Iconfinder or Flaticon. These files usually contain a rich set of metadata and paths that include points used by designers. Unless you are using those specific paths and points in your application, they can be optimized to further reduce the file size.
There is a really awesome tool called SVGO which will process and optimize your SVG files. It can remove excessive markup and metadata, optimize and clean paths, and minify the output. It can be included in your build process, or run independently.
Even better than the command line interface, is a website created by Jake Archibald (@jaffathecake), called "SVGO Missing GUI" or SVGOMG.
From here we can upload or paste our source code into the REPL, toggle the options, and easily gather the output for use in our HTML and JavaScript.
In the example above, we can see how it saved 68% for such a small icon. When you're working with a lot of icons, or larger vector graphics, it can make a noticeable impact on your overall application.
Better bundle sizes mean your web app is faster, more responsive, and reaches more customers around the world. 68% is great!If you're building your web application with React, it is not as easy to copy and paste the SVG output into your application. React uses the naming convention from JavaScript objects to create HTML elements. Instead of stroke-width, we use strokeWidth in JSX.
Fixing all of those attributes takes too much time, and so enter: React SVGR
Similarly, React SVGR is also a node API, command line client, and most importantly - a GUI playground. Using this tool, we can paste our SVG output from SVGO and it will output a React component.
In the example above, we can see that SVGR does have an integration with SVGO if you have a JSON config object on hand. However, I rarely carry that around with me as I am developing - so I generally optimize with SVGO first and then paste the output into SVGR.
With these tools, you can deliver the most optimized version of vector graphics in your web application. Whether you're using React.JS, or vanilla HMTL and JavaScript - these tools have you covered.
Now we're cooking with some gas - You
Photo by Andrej Lišakov