Back to the article · Zurück zum Artikel (Deutsch)
Example 13: Declarative Shadow DOM, upgrade path
Rule 6: Don't create content with JavaScript alone
The server delivers the shadow root (<template shadowrootmode="open">), the component is only defined after the HTML.
How to try it
- Open the console of the developer tools.
- The warning sign and the text are there: the shadow root from the server is kept, and the text from the light DOM is slotted into it.
- The log says that the shadow root already existed in the constructor.
console.log() and errors on this page, the same text as in the developer toolsconstructor: shadowRoot present: true
Live example
Source
<my-alert>
<template shadowrootmode="open">
<span>⚠</span>
<slot></slot>
</template>
The build is still running.
</my-alert>
<script type="module">
class MyAlert extends HTMLElement {
constructor() {
super();
console.log('constructor: shadowRoot present:', !!this.shadowRoot);
this.shadowRoot ?? this.attachShadow({ mode: 'open' }).append('JS-built');
}
}
customElements.define('my-alert', MyAlert);
</script>