CKTIS / JavaScript
Custom element `disconnectedCallback()`
Use `disconnectedCallback()` to release resources tied to a custom element’s connection to a document, while keeping the instance ready to reconnect.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
class MyElement extends HTMLElement {
disconnectedCallback() {
// Release resources tied to the current connection.
}
}
customElements.define("my-element", MyElement);disconnectedCallback() is an optional instance lifecycle method on a registered custom element. The browser calls it with no arguments and with this set to the element when it loses its connection to a document, for example when an ancestor is removed. Hiding the element or creating it without inserting it does not trigger the callback. This is a web platform API, not part of ECMAScript 2024.
Start connection-scoped work in connectedCallback() and undo it in disconnectedCallback(): stop timers, disconnect observers, and remove listeners from external targets. For removeEventListener(), match the original target, event type, function object, and capture value. Disconnection does not destroy the instance: it can reconnect, so make cleanup safe to repeat.
An ordinary move within a document using Node.insertBefore() can trigger disconnectedCallback() followed by connectedCallback(). If the browser supports Element.moveBefore() and the element defines connectedMoveCallback(), a state-preserving move with that API calls connectedMoveCallback() instead of the other two. Check support in your target browsers.
Examples
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Custom element disconnection</title>
</head>
<body>
<pre id="result"></pre>
<script>
const source = new EventTarget();
let count = 0;
class CktisPingCounter extends HTMLElement {
#onPing = () => { count += 1; };
connectedCallback() {
source.addEventListener("ping", this.#onPing);
}
disconnectedCallback() {
source.removeEventListener("ping", this.#onPing);
}
}
customElements.define("cktis-ping-counter", CktisPingCounter);
const counter = document.createElement("cktis-ping-counter");
const counts = [];
const probe = () => {
source.dispatchEvent(new Event("ping"));
counts.push(count);
};
document.body.append(counter);
probe();
counter.remove();
probe();
document.body.append(counter);
probe();
counter.remove();
probe();
const output = counts.join(", ");
document.getElementById("result").textContent = output;
console.log(output);
</script>
</body>
</html>Result
1, 1, 2, 2
Save the full snippet as an HTML file and open it in a browser. Both appends use the same instance. A `ping` increases the count only while the element is connected, so the expected output is `1, 1, 2, 2`.
Related lessons
- JavaScript · Lesson 39 · Intermediate · Version: 3