With the demise of IE, all modern browsers now support Web Components.
You have the ability to craft your very own <load-svg>
Web Component for fetching external SVG files, eliminating the necessity for symbol
and use
tags and seamlessly integrating them into your HTML document.
Utilizing shadowDOM is not mandatory, preventing any leakage of styles in or out and addressing the perennial issue of duplicate ID values in SVG files.
Minimal code required:
Tip: Embed this code within a <script>
tag in the <head>
customElements.define("load-svg", class extends HTMLElement {
// declare default connectedCallback as async so await can be used
async connectedCallback(
// call connectedCallback with parameter to *replace* an existing SVG
src = this.getAttribute("src"),
// attach a shadowRoot if none exists (|| prevents displaying error when moving Nodes)
shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
) {
// load SVG file from src="" async, parse to text, add to shadowRoot.innerHTML
shadowRoot.innerHTML = await (await fetch(src)).text()
// append optional <tag [shadowRoot]> Elements from inside <load-svg> after parsed <svg>
shadowRoot.append(...this.querySelectorAll("[shadowRoot]"))
// if "replaceWith" attribute
// then replace <load-svg> with loaded content <load-svg>
// childNodes instead of children to include #textNodes also
this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes)
}
})
path { fill: red }
load-svg,svg { display:inline-block; width:150px }
<load-svg src="https://svg-cdn.github.io/heart.svg"></load-svg>
<load-svg src="https://svg-cdn.github.io/heart.svg">
<style shadowRoot>
path { fill: green }
</style>
</load-svg>
<load-svg replaceWith src="https://svg-cdn.github.io/heart.svg"> </load-svg>
There are two optional attributes available:
shadowRoot
transfers the DOM element to shadowDOM
replaceWith
substitutes the <load-svg>
DOM element with the content of the loaded file (in this case, your <svg>
)
Keep in mind: this Web Component is not limited to *.svg
files; you have the capability to load any type of file.