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
- 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.
- Check that
connectedCallbackcomes before the last line.
console.log() and errors on this page, the same text as in the developer toolsconnectedCallback 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>