I have an svg uploaded to my website and I want to embed it into my html so that it can have the structure of svg and path:
<svg>
<path id="svgPath"/>
</svg>
I managed to do it with image
<svg width="1920" height"720">
<image id="imgId" xlink:href="srclink" width="1920" height="720" />
</svg>
And when I query that image, I don't have the same methods that I have as for a path element. For example, I don't have the .getTotalLength()
const path = document.querySelector("#pathId");
path.getTotalLength(); // will work
const img = document.querySelector("#imgId");
img.getTotallength(); // does not work
I can insert it with Javascript too, if there is a way to do that while loading it from the srclink.
I need to be able to access the path as the rest of my code is dependent on that.
If it is an external *.svg file, A native Web Component <load-file> can fetch it and inject it in the DOM; either in shadowDOM or replacing the <load-file> Element, thus becoming part of the DOM you can access and style with CSS.
customElements.define("load-file", class extends HTMLElement {
// declare default connectedCallback as sync so await can be used
async connectedCallback(
// call connectedCallback with parameter to *replace* SVG (of <load-file> persists)
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)
}
})
Full explanation in Dev.To post: 〈load-file〉Web Component, add external content to the DOM