Lifecycle Callbacks
Hook into connected, disconnected, and attribute changes.
The Element Lifecycle
Custom elements have a defined lifecycle. The browser calls special methods on your class at key moments:
connectedCallback— added to the DOMdisconnectedCallback— removed from the DOMattributeChangedCallback— an observed attribute changesadoptedCallback— moved to a new document
connectedCallback
connectedCallback runs every time the element is inserted into the document. This is the ideal place to render content, fetch data, or attach global listeners.
It can fire multiple times if the element is moved around.
class StatusBadge extends HTMLElement {
connectedCallback() {
this.textContent = 'Online';
console.log('badge added to page');
}
}
customElements.define('status-badge', StatusBadge);All lessons in this course
- Defining Custom Elements
- Lifecycle Callbacks
- Shadow DOM and Encapsulation
- Templates and Slots