0

I have an SVG sprite file which was supplied by designers for my app. The convention they'd like me to use to render their SVG icons is to load the sprite at the top of the <body> element and then render icons like this:

<svg class="u-icon-gear-dims">
    <use xlink:href="#gear"></use>
</svg>

This works when I add the SVG sprite inline, that is, plop the entire contents of the SVG sprite into my template.html file. Adding the sprite inline makes the html file ugly but, more significantly, having to manually do it raises maintainability concerns.

I'm currently referencing the individual SVGs directly to render icons, but this has performance implications as there is often a split second delay when the icon has not yet been loaded.

I found this SO topic, but there does not appear to be a viable answer.

FWIW, our app uses webpack and I'm currently trying to load the SVG sprite into a template HTML file.

How can I dynamically load an SVG sprite from a file in an HTML file?

mellis481
  • 4,332
  • 12
  • 71
  • 118
  • Look at one of the [webpack template loaders](https://webpack.js.org/loaders#templating). [pug includes](https://pugjs.org/language/includes.html) or https://github.com/asnowwolf/markup-inline-loader should work. – ccprog Mar 19 '19 at 14:58
  • @ccprog are you aware of any packages that would work with `rollup.js`? Specially if you load/include/require the SVG dynamically (based on a variable and not a long list of if then /swtich)? – Jujubes Sep 03 '20 at 20:54

1 Answers1

0

Are you using PHP? There are methods for including SVG markup inline using backend languages. https://sheelahb.com/blog/how-to-get-php-to-play-nicely-with-svg-files/

Clark Nelson
  • 171
  • 1
  • 6
  • No. I did see the PHP solution before. This is a React app, although the template file I'm trying to load the SVG into it pure HTML. – mellis481 Mar 19 '19 at 14:42
  • Can you create a react component that simply serves the SVG code? Isn't react designed to include templates like this? – Clark Nelson Mar 19 '19 at 15:01