Skip to content

Web Components

The lifecycle of a custom element: when the browser calls constructor, connectedCallback, attributeChangedCallback, adoptedCallback and disconnectedCallback.

2 min readUpdated

Web Components let you define your own HTML elements, such as <user-card>, with standard browser APIs and no framework. A custom element is a class that extends HTMLElement and is registered with customElements.define. The browser then calls a fixed set of methods on it at certain moments, the lifecycle callbacks. This note describes each of them and shows them together in one class.

Lifecycle callbacks

constructor()

Creates and initialises the instance. It is the first method in the lifecycle and runs once for each element, when the element is created or when an existing element in the page is upgraded after customElements.define is called. Call super() first. Set up initial state, event listeners and the shadow root here, but do not read attributes or add children: the element may not be in the document yet. The specification recommends doing as much setup as possible in connectedCallback instead.

connectedCallback()

Called each time the element is added to the document. It can run more than once, for example when the element is moved, so guard one-time work with a flag. This is the place to render content, read attributes and start fetching data.

attributeChangedCallback(name, oldValue, newValue)

Called when an observed attribute is added, changed, removed or replaced. It receives the attribute’s name, its old value and its new value (null when the attribute is absent). Only attributes listed in the class’s static observedAttributes array trigger it. The array is defined on the class itself, not in the constructor:

static observedAttributes = ['attribute1', 'attribute2'];

Older code uses a static getter for the same purpose:

static get observedAttributes() { return ['attribute1', 'attribute2']; }

If an observed attribute is present in the HTML, the callback also runs once when the element is parsed, before connectedCallback.

adoptedCallback()

Called when the element is moved to a new document, for example with document.adoptNode() from an <iframe> into the main page. It is rarely needed.

disconnectedCallback()

Called each time the element is removed from the document. Undo what connectedCallback started: remove listeners on window or document, stop timers and cancel pending requests.

connectedMoveCallback()

A newer, optional callback. When it is defined, moving the element with Element.moveBefore() calls it instead of disconnectedCallback followed by connectedCallback, so the element keeps its state. Check browser support before you rely on it.

Example

This element shows its size attribute and logs each lifecycle step:

my-element.js
class MyElement extends HTMLElement {
static observedAttributes = ['size'];
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
connectedCallback() {
console.log('added to the page');
this.render();
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(`${name} changed from ${oldValue} to ${newValue}`);
this.render();
}
adoptedCallback() {
console.log('moved to a new document');
}
disconnectedCallback() {
console.log('removed from the page');
}
render() {
this.shadowRoot.textContent = `Size: ${this.getAttribute('size') ?? 'unset'}`;
}
}
customElements.define('my-element', MyElement);

Use it in HTML like any other element. The name of a custom element must contain a hyphen:

<my-element size="large"></my-element>

References

Related notes

13 min read

Frontend Checklist

A pre-launch checklist for a landing website: meta tags, HTML, CSS, JavaScript, media, performance, SEO, accessibility, security and Hugo builds.

  • Web & Frontend
3 min read

SVG

Recolour an inline SVG background image from Sass: a mixin that URL-encodes the colour as %23 so one logo works in any colour.

  • Web & Frontend
13 min read

Jakarta Faces (JSF)

Jakarta Faces (JSF) recipes: WebSocket push, validators with injection, resource handling, component binding, java.time and scopes.

  • Java & Jakarta EE
  • Web & Frontend

Type to search the whole site.