Split in the shadows

Drawing your favorite picture with SVG you may rely on a reference, on a shape you define with the id attribute and later include with the use element and the href attribute.

The option is quite convenient. You can centralize the definitions in the early stages of the svg container, perhaps in the defs element to avoid the immediate render, and then you just have to mind the unique ID.

But you need to be careful when you repeat this effort with web components, and specifically with the Shadow DOM. The API offers a way to encapsulate code, to separate HTML, CSS and JavaScript from the rest of the page. And in this instance the cut is hard to a fault.

The good news: encapsulation. In the shadow context, in the shadow root, you have a clean slate. In terms of CSS, for instance, even the more general selectors will work. Style properties won’t leak in, nor escape the separate tree.

The bad news: encapsulation. The connection with the light document is severed. And while there might be more than one way to style elements across the shadows, the reference to the id attribute is completely lost.

Should you define a shape in the shadows, you won’t be able to use it outside. Only within.

Inspector #shadow-root <path id="star" /> ... <use href="#star" />
Inspector #shadow-root <path id="star" /> <use href="#star" /> ...

Should you want to see the result in the light, you will have to define the companion in the bright environment first.

Inspector #shadow-root <path id="star" /> ... <use href="#star" />
Inspector #shadow-root ... <path id="star" /> <use href="#star" />

You can even define the element twice, but be warned. While there is no conflict and you can keep both, but you’ll end up using either.