'How to use the whole SVG with a <use> tag?

I have an SVG file freshly exported from Figma.

  1. I don't want to inline it because it's used on multiple places.
  2. I can't specify it as <img src="..."> because I need to style its parts.

So, I tried to include it like this:

<svg>
  <use xlink:href="http://example.com/myshape.svg"></use>
</svg>

But it doesn't work. MDN states:

The <use> element takes nodes from within the SVG document, and duplicates them somewhere else.

It takes nodes from the document. With SVG sprites, you have <symbol> tags with id attributes and you reference them with <use> by adding xlink:href="mysprite.svg#symbolid". However, here I need to use the whole document, I.E. the root node. Is there a way to do that?

It would also be great if I don't have to edit the source SVG file, as it's uploaded via an admin panel by the user. It's just a file exported from any vector graphics program.



Solution 1:[1]

SVG 2 (when implemented in browsers) will allow to reference another SVG file without any fragment identifier:

New in SVG 2: An href without a fragment allows an entire SVG document to be referenced without having to ensure that it has an ID on its root element.

Before:

<!-- my-vector.svg -->

<svg id="icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
  <circle r="10" cx="12" cy="12" />
</svg>
<use href="my-vector.svg#icon"></use>

After (there will be no need to define id="..." on the svg):

<!-- my-vector.svg -->

<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
  <circle r="10" cx="12" cy="12" />
</svg>
<use href="my-vector.svg"></use>

SVG 2 seems to be in the process of development in major browsers (see this Chrome feature and specifically this Chromium issue: Issue 366545: [SVG2] Allow to reference entire files).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mahozad