skip to content
dz

Back to the article · Zurück zum Artikel (Deutsch)

Example 05: Callbacks have run when append() returns

Rule 3: Don't wait for callbacks with setTimeout

The connectedCallback sets a ready attribute. The script reads it directly after append(), without any timer.

How to try it

  1. Open the console of the developer tools (F12, Cmd+Opt+I on a Mac). The "Console output" box on this page shows the same lines.
  2. Check that connectedCallback comes before the last line.
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
connectedCallback
after append, ready: true

Live example

Source

<script type="module">
	class StatusLight extends HTMLElement {
		connectedCallback() {
			this.setAttribute('ready', '');
			console.log('connectedCallback');
		}
	}

	customElements.define('status-light', StatusLight);

	const light = document.createElement('status-light');
	document.body.append(light);
	console.log('after append, ready:', light.hasAttribute('ready'));
</script>