Open Template Open Template Open Template

How to show svg symbol from external file after appendChild

276 Views Asked by At

So, basically i want to use to create some component which contains svg symbol.

<button onclick="openWindow('#my-template')">Open Template</button>
<template id="my-template">
    <div id="my-div">
        <div>My fancy stuff</div>
        <svg>
            <use href="/svg/icons.svg#my-icon"/>
        </svg>
    </div>
</template>

As you see i refer to external svg icons file <use href="/svg/icons.svg#my-icon"/> which works perfect in regular html. But then i want to do this basic javascript function, icon itself is not visible after appending to DOM.

function openWindow(e) {
    let content = document.querySelector(e).content;
    document.body.appendChild(content.cloneNode(true));
}

So basically all what it does is cloning template content and appending to document body. It works perfectly except that icon itself is not rendered. There is a svg node in DOM created, but icon is not visible on the screen. When i include inline <svg> document with symbols listed in my current HTML document and refer to icon with <use href="#i-my-icon"/> it works as expected. Icon is visible. How can i be able still to use external .svg file in this case? I don't want to deal with inlining svg icons directly or including icon set in every html document or template.

1

There are 1 best solutions below

2
enxaneta On

Please try using an object:

function openWindow(e) {
    let content = document.querySelector(e).content;
    document.body.appendChild(content.cloneNode(true));
}
<button onclick="openWindow('#my-template')">Open Template</button>
<template id="my-template">
    <div id="my-div">
        <div>My fancy stuff</div>
<object id="svgContent" type="image/svg+xml"
data="https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/cat.svg#redcat">
</object>
    </div>
</template>