by mablopoule · 5y ago · 0 comments
<!-- Should be in all your pages -->
<svg style="display: none" aria-hidden="true">
<defs>
<symbol id="icon-circle" viewBox="0 0 20 20"><circle fill="currentColor" cx="10" cy="10" r="10" /></symbol>
<!-- other icons here -->
</defs>
</svg>
<!-- In some other template -->
<button>
<svg class="icon"><use xlink:href="#icon-circle"></use></svg>
<span>foobar</span>
</button>
<!-- in your CSS -->
.icon { width: 1em; height: 1em; }
This approach I feel has most of the advantages of inlined SVG (mostly context-dependent colors) while avoiding most of the clutter, and is not heavily reliant on a specific JS-based workflow (thought we do need to includes our <def> somewhere in all pages)You can give my library, svg-loader, [1] a try. It's a single line of javascript that makes it really easy to load external SVGs as inline elements. The syntax is even shorter and you avoid all the problems of external SVGs.
I use Affinity Designer for this. It exports artboards using a trivially detectable pattern, which can be easily turned into symbol elements in a compilation step.
I made a feature request for an option to do this natively, but it never got any traction.
some advanced features of SVG, such as filters, are very much YMMV to this day. But for simple logos and icons there isn't much to worry about.
Nice overview here too http://tutorials.jenkov.com/svg/use-element.html
https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use...
<use xlink:href='icons.svg#foo'/>
Theoretically the browser should only download that file once, just as with multiple img elements referencing the same image. I haven't seen that approach much in the wild, though.