A custom element’s constructor runs when the browser creates or upgrades the element. It is a place to initialize internal state, attach a shadow root, and bind handlers. Connection is a separate step: connectedCallback() runs when the element is inserted into a document. section 9.2.1
Register the class or constructor function with customElements.define(name, constructor). The name must contain a hyphen and must not already be registered. Once registered, the browser can instantiate the class from its HTML tag or through document.createElement(). An unregistered tag does not raise an error; it remains an empty HTMLElement rather than an instance of the intended class. section 7.6.3
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 example calls super() before attaching a shadow root in constructor(). It renders after connection and checks isConnected before rendering in response to an attribute change, which can occur before connectedCallback(). section 9.2.1
Prefer attributes and properties over arguments passed with new: constructor arguments will be undefined when the same element is instantiated from HTML. Keep the component’s public contract in its attributes, properties, methods, and events rather than relying on a JavaScript-only creation path. section 7.6.3 section 7.5.1

















