The connectedCallback and disconnectedCallback
Run code when a custom element is added or removed from the DOM.
Element Lifecycle Callbacks
Custom elements expose four lifecycle hooks: connectedCallback, disconnectedCallback, attributeChangedCallback, and adoptedCallback. They mirror the well-known mount/unmount/update points of any component model.
connectedCallback Fires on Insertion
connectedCallback runs every time the element is inserted into the DOM tree. This is the right place to read attributes, render content, attach event listeners, and start any timers or subscriptions.
class Timer extends HTMLElement {
connectedCallback() {
this.start = Date.now();
this.interval = setInterval(() => this.render(), 1000);
this.render();
}
render() {
this.textContent = Math.floor((Date.now() - this.start) / 1000) + "s";
}
}All lessons in this course
- Defining Elements with customElements.define
- The connectedCallback and disconnectedCallback
- Observed Attributes and attributeChangedCallback
- Extending Built-in Elements