A custom element may be created, inserted, updated, removed, and inserted again. Lifecycle callbacks give its class a place to respond to those changes. They work alongside attributes, properties, methods, and events: callbacks manage the element’s response to its surroundings, while those APIs form its contract with the host page. section 7.5.1 section 9.2.1
Put work where the browser can reliably trigger it:
- Use the constructor when the element is created or upgraded. Call super(), then initialize internal state, attach a shadow root if needed, or bind handlers. section 9.2.1
- Use connectedCallback() for work needed each time the element enters a document, and disconnectedCallback() for work needed each time it leaves. section 9.2.1 section 9.10
- Use attributeChangedCallback(name, oldValue, newValue) to react to changes in observed attributes. Use adoptedCallback() when the element moves to a different document. section 9.2.1
Do not assume connection precedes an attribute callback: an element upgraded with attributes already in its markup can receive attributeChangedCallback() first. Check isConnected, or an internal initialized flag, before DOM work that requires a connected element. Because connection and disconnection can recur, treat them as repeatable transitions rather than one-time setup. section 9.2.1
Listing 9.2 A custom element showing the main lifecycle callbacks
class LifecycleDemo extends HTMLElement {
static observedAttributes = ["status"];
constructor() {
super();
console.log("1. constructor");
this.attachShadow({ mode: "open" });
}
connectedCallback() {
console.log("2. connectedCallback");
this.render();
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(`3. attributeChangedCallback: ${name} changed`);
if (this.isConnected) {
this.render();
}
}
disconnectedCallback() {
console.log("4. disconnectedCallback");
}
adoptedCallback() {
console.log("5. adoptedCallback");
}
render() {
this.shadowRoot.innerHTML =
`<p>Status: ${this.getAttribute("status") || "none"}</p>`;
}
}
customElements.define("lifecycle-demo", LifecycleDemo);
The listing registers an HTMLElement subclass, observes a status attribute, renders on connection, and guards attribute-triggered rendering with isConnected. Its numbered log labels illustrate the callbacks, not a guaranteed callback order. section 9.2.1
