Dirk Boer
Dirk Boer

Reputation: 9065

Is it possible to refer to an SVG defined somewhere else in the HTML document?

I have huge dynamic lists that refer to a large amount of seperate (generated) SVGs (stylized acronyms).

I do not like to put the the generated SVGs in seperate files, because it will create hundreds/thousands of requests. Even with HTTP/2 somehow I would not like this solution. I have the feeling it creates unnecessary overhead.

Everytime inlining the full SVG I also do not like. It creates duplicate data for all the same acronyms (an item can appear multiple times at the page) and next to that it is a highly dynamic page: I have the feeling changing a background image is a lot faster then changing the DOM with the SVG.

So: is it possible to refer to a SVG defined somewhere else in the document?

I'm looking for something similar to:

<!-- generated by server -->
<div style="display: hidden;"> 
    <svg id="acronym-abc">
        [...]
    </svg>
    <svg id="acronym-xyz">
        [...]
    </svg>
</div>

<!-- generated by client -->
<ul>
    <li style="background: SVG(id=acronym-abc)"></li>
    <li style="background: SVG(id=acronym-xyz)"></li>
    <li style="background: SVG(id=acronym-abc)"></li>
    [...]
</ul>

UPDATE

It was not clear from my question, but I have the preference for something that I can use in combination with background-image and support for IE9. Otherwise I'll accept the answer from @web-tiki.

Upvotes: 2

Views: 127

Answers (1)

web-tiki
web-tiki

Reputation: 103770

You could use the <symbol> element and refer to each symbol with the <use> tag.
This won't work as a background image but it will allow you to only have on instance of each symbol. And you will also have control over the styles of the symbol each time you refer to it.

Here is an example :

<svg width="0" height="0">
  <symbol id="circle" viewBox="0 0 2 2">
    <circle cx="1" cy="1" r=".7" />
  </symbol>
  <symbol id="square" viewBox="0 0 2 2">
    <path fill="darkorange" d="M.5 .5 H1.5 V1.5 H.5z" />
  </symbol>
</svg>
<p>
  <svg width="50" height="50"><use xlink:href="#circle" /></svg>
  <svg width="50" height="50"><use xlink:href="#circle" fill="teal" stroke="red" stroke-width=".1"/></svg>
  <svg width="50" height="50"><use xlink:href="#square" /></svg>
  <svg width="50" height="50"><use xlink:href="#square" fill-opacity=".5"/></svg>
</p>

More info on MDN :

Upvotes: 4

Related Questions