ARTICLE AD BOX
I have many instances of a custom element which uses a Shadow DOM. In their shadow DOM lives an <svg> element, which needs to display the same shapes with the same filters for every instance of the custom element.
In order to improve performance and simplicity, I'd like to define these shapes and filters only once and reuse them in every SVG element. I tried to define them in the main document, but the Shadow DOMs don't seem to be able to access them.
How can I reuse them? I cannot include them from a separate file, since I need to manipulate the shapes and filters via JavaScript.
Non-working example:
7
id=shape and use=#shape can not be used accross (user-defined) shadowRoots
If you want to create new elements from templates then:
use the <template> tag (content is NOT parsed by the browser!!)containing your SVG content (and) create the elements with Web Components
creating your SVG content
Example <svg-shape> Web Component combining both patterns:
Pitfalls
Namespace! Namespace! SVG must be created with the correct Namespace "http://www.w3.org/2000/svg"
Nice-to-know: When
you insert an <svg> String tag into an HTML document, the DOM parser WILL SET the correct SVG Namespace That
is why the <template> contains that <svg> tag. Otherwise <rect> and <circle> would be HTMLUnknownElements.
For HTML Nodes .nodeName is always UPPERCASE, but in SVG Namespace it is lowercase!
In above code include="circle,circle" create overlapping circles!
2 Comments
That only works for standalone graphics though. You can't compose a new graphic reusing the other symbols and e.g. apply a single viewBox over these, or a single filter like OP is trying to do. And it really doesn't work for OP's case. Every element is "cloned", and thus applying a change on one won't apply on the others. That's basically the same as having the markup stored in a JSON.
2025-11-26T00:16:33.16Z+00:00
Explore related questions
See similar questions with these tags.

