Back to the article · Zurück zum Artikel (Deutsch)
Example 14: Declarative Shadow DOM, parser path
Rule 6: Don't create content with JavaScript alone
Like 13, but the component is defined before the HTML. The constructor runs before the parser has seen the <template>.
How to try it
- Open the console of the developer tools.
- The console shows a parser error (in Chromium: "A second declarative shadow root cannot be created on a host", the wording may differ in other browsers).
- What you see is the content built with JavaScript ("JS-built") instead of the shadow root from the server.
console.log() and errors on this page, the same text as in the developer toolsconstructor: shadowRoot present: false
Live example
Source
<script>
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>
<my-alert>
<template shadowrootmode="open">
<span>⚠</span>
<slot></slot>
</template>
The build is still running.
</my-alert>