feature: `element.getShadow(opts)`
This would be an alternative to element.attachShadow(opts). It would be similar to canvas.getContext in that if a root is not already created/attached, it will create/attach the root before returning the root. If a root is already created, the existing root will be returned. This would make it easier to write code like this:
class MyEl extends HTMLElement {
connectedCallback() {
this.getShadow(opts).innerHTML = `...`
}
}
without having to write extra code to handle whether or not a root already exists.
On a related note, maybe a similar utility would be nice for ElementInternals?
Hmm, that makes closed roots easy to get, doesn't it. Who actually uses closed roots?
Maybe this is better as an ElementInternals API? For example:
#internals = this.attachInternals()
connectedCallback() {
this.#internals.getShadow(opts).innerHTML = `...`
}
Why create it on document connection and not when the element is created?
You could just do the following right? (See here)
const shadowRoot = this.#internals.shadowRoot ?? this.attachShadow({ ...opts });
Whether it is worth abstracting this into a new method I'm not sure. Although I would ask are empty shadow roots really so expensive that you can't just attach them unconditionally in the constructor? i.e.:
#internals = this.attachInternals();
constructor() {
this.attachShadow({ ...opts });
}
connectedCallback() {
this.#internals.shadowRoot.innerHTML = `...`;
}