SVGs are great for performance. It's good to use SVGs for icons/logos and all sort of illustrations but more than once i've come across this argument that inline SVGs are a pain because they bloat the markup and are hard to handle whilst the solutions like icon-font libraries(eg: font awesome) are much more convenient to use.
I realized that people are ready to compromise with the performance but not with the ease of use.
Here’s a little nugget of advise kind of story for such developers to make it easy for them to get started with using SVGs today.
Let's get started!
The problem
SVGs markup is hard to use
Using fontawesome icons is much easier to use compared to the complex SVG markup, you just have to include its CSS file and start using the icons in your markup like this:
<i class=“fa fa-icon”></i>
For an SVG though, its a different story.
The SVG code for the same icon could look something like this:
<svg xmlns="w3.org/2000/svg" viewBox="0 0 700 400" id="icon">
<path fill="#000" stroke="black" stroke-width="1" d="........." />
<path fill="#FFF" stroke="black" stroke-width="1" d="........." />
...
...
</svg>
Looks much more complex right?
Well that's what we're going to solve now.
The solution
Simplify & Combine the markup
Let's simplify the SVG markup.
An SVG looks something like this:
<svg xmlns="w3.org/2000/svg" viewBox="0 0 700 400" id="icon">
<!-- svg shapes -->
</svg>
Instead of having multiple <svg>
tags for different elements, we will wrap them all into a single <svg>
tag.
Each individual <svg>
tag can be replaced with a <symbol>
tag with a unique id and wrapped inside a single parent <svg>
element.
Wrapping multiple SVGs would look something like this:
<svg version="1.1" xmlns="w3.org/2000/svg" xmlns:xlink="w3.org/1999/xlink">
<defs>
<symbol id="icon-1" viewBox="0 0 700 400">
<!-- svg shapes -->
</symbol>
<symbol id="icon-2" viewBox="0 0 300 400">
<!-- svg shapes -->
</symbol>
....
....
</defs>
</svg>
Now this main <svg>
can be put inside the <body>
tag or be saved as a .svg
file for further use.
<use>
the SVG
As our SVG markup now is combined now, you can just reference any inner <symbol>
using the <use>
tag and it would just display the relevant svg.
There are two ways of doing this.
I. Referencing in same document
When you put the parent <svg>
inside the <body>
, you can reference a symbol inside the svg by using its id.
Which would look something like this:
<svg><use xlink:href="#icon-1"></use></svg>
II. External Referencing
If you've saved the <svg>
content as a .svg
file, you can reference the relevant symbol by putting the file path followed by the symbol id.
Which would look something like this:
<svg><use xlink:href="icons.svg#icon-1"></use></svg>
Pretty convenient, right?
Here's a pen with some example code: codepen.io/alkshendra/pen/VaVVzm?editors=1100
Hope you enjoyed reading this, let me know your thoughts in the comments. 😊