skip to content
dz

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

  1. Open the console of the developer tools.
  2. 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).
  3. What you see is the content built with JavaScript ("JS-built") instead of the shadow root from the server.
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: false

Live example

The build is still running.

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>