skip to content
dz

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

  1. Open the console of the developer tools.
  2. 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.
  3. The log says that the shadow root already existed in the constructor.
Console output mirrored from console.log() and errors on this page, the same text as in the developer tools
Expected output what the lines above should say
constructor: shadowRoot present: true

Live example

The build is still running.

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>