connectedCallback and disconnectedCallback
Learn when connectedCallback and disconnectedCallback run, why they can run many times, and how to clean up listeners and timers with AbortController.
- 01Say when each callback runsPredict what runs when an element is added, removed, moved, or hidden.
- 02Write setup that can run many timesGuard one-time work, and check
isConnectedbefore work that might come too late. - 03Clean up everything the element startedStop timers and remove outside listeners with one
AbortControllerfor each time the element joins the page.
What do connectedCallback and disconnectedCallback do?
Asha's online shop for Leaf and Kettle shows a timer next to each tea that's brewing. Ravi wrote it, a tag called tea-timer. It counts the seconds since the tea went in. When Asha serves the tea, her shop takes the timer off the page.
Then she opens the console. It still says Tick: 3 s, then Tick: 4 s, once a second. The timer is gone from the page. So what is still ticking? And how can a component know that it has left the page?
connectedCallback() is a method the browser calls each time your element is put into the page. disconnectedCallback() is the method it calls each time the element is taken out. Start work in the first one. Stop it in the second one.
Both are lifecycle callbacks. You write them, and the browser calls them at set moments in the element's life. You never call them yourself. Here is a badge that prints a line from each:
<p>Teas: </p> <script> class TeaBadge extends HTMLElement { connectedCallback() { console.log(`${this.textContent} joined the page`); } disconnectedCallback() { console.log(`${this.textContent} left the page`); } } customElements.define("tea-badge", TeaBadge); const badge = document.createElement("tea-badge"); badge.textContent = "Organic"; const p = document.querySelector("p"); p.append(badge); badge.remove(); p.append(badge);</script>- Lines 5 to 7 are
connectedCallback(). It prints the badge's text andjoined the page. - Lines 8 to 10 are
disconnectedCallback(). It printsleft the page. - Line 14 makes a badge by name, the way Asha's shop does. It isn't on the page yet, so nothing prints.
- Line 17 puts the badge in the paragraph, which is on the page. The console prints
Organic joined the page. - Line 18 takes it out again. The console prints
Organic left the page. - Line 19 puts it back.
connectedCallback()runs a second time.
The browser called each method right when a line changed the page. And it called connectedCallback() twice, once for each time the badge joined.
connectedCallback() runs. Each time it leaves, disconnectedCallback() runs. Line 19 runs the first one a second time.At the tea shop, the kettle moves around. Each time Ravi puts it on a counter, he plugs it in. Each time he puts it away, he unplugs it first. To move it to another counter, he unplugs it and plugs it in again. If he forgets to unplug it, it stays on in the cupboard.
- In real life: Putting the kettle on a counter and plugging it in
- In JavaScript:
connectedCallback() - In real life: Unplugging it before you put it away
- In JavaScript:
disconnectedCallback() - In real life: Moving it to another counter
- In JavaScript: Taking the element out and adding it somewhere else
- In real life: A kettle left switched on in the cupboard
- In JavaScript: A timer that keeps going after the element left
connectedCallback() runs each time the element joins the page. disconnectedCallback() runs each time it leaves. Whatever the first one starts, the second one stops. Both can run many times for one element.
In lesson 3.2, the constructor left work for later: reading attributes and adding content. This lesson shows when "later" comes, how often it comes, and how to clean up after it.
When does connectedCallback run?
The browser calls it when the element becomes connected. That's the standard's word for "inside a document", the page the browser shows. Every element has an isConnected property. It's true when the element is in a document, and false when it isn't.
Being inside a parent isn't enough. The parent must be on the page too:
<p>Teas: </p> <script src="tea-badge.js"></script> <script> const badge = document.createElement("tea-badge"); badge.textContent = "Organic"; const box = document.createElement("div"); box.append(badge); console.log("In a box:", badge.isConnected); document.querySelector("p").append(box); console.log("On the page:", badge.isConnected);</script>- Line 3 loads
tea-badge.js, the second tab. It's the badge from the first example, in its own file. - Lines 6 and 7 make a badge called Organic.
- Lines 8 and 9 make a box, a
<div>, and put the badge in it. The box itself isn't on the page. - Line 10 prints
In a box: false. The badge has a parent, but it isn't connected. No callback has run. - Line 11 puts the box in the paragraph. Now the badge is in the document. Its
connectedCallback()printsOrganic joined the page. - Line 12 prints
On the page: true.
A badge in a box off the page is like a letter in an envelope you haven't posted. It has a home, but it isn't going anywhere yet.
So connectedCallback() runs for any change that brings the element into the document:
- The parser reads its tag, after
customElements.define()has run. define()upgrades a tag that was already on the page. The constructor runs first, thenconnectedCallback().append(),prepend(),before(),insertBefore(), orreplaceWith()puts it on the page, or puts in a parent that holds it.innerHTMLwrites its tag inside an element that's on the page.- It goes into a shadow root whose element is on the page. A shadow root is a private tree inside an element. MDN's page on
isConnectedshows this case.
Each time, the element has just joined the page, and the tag's attributes are already there. That's why lesson 3.2 moved reading them here.
Why it matters: a badge made by name, as in Asha's shop, waits quietly. Its setup runs only once it joins the page, with its attributes already set.
When does disconnectedCallback run?
It runs when a connected element stops being connected. Taking the element out is one way. Taking out something it's inside is another:
<p>Teas: <tea-badge>Organic</tea-badge> <tea-badge>Fair trade</tea-badge></p> <script src="tea-badge.js"></script> <script> const p = document.querySelector("p"); p.textContent = "Sold out"; console.log("Badges on the page:", document.querySelectorAll("tea-badge").length);</script>- Line 1 puts two badges in a paragraph.
- Line 3 loads
tea-badge.js. The browser upgrades both badges, and each printsjoined the page. - Line 7 swaps everything in the paragraph for the words Sold out.
- Both badges print
left the page. Then line 8 printsBadges on the page: 0.
Line 7 never named the badges. They left as part of the paragraph's old content. The browser runs disconnectedCallback() for every custom element that leaves, however deep it sits. The same goes for innerHTML = "", replaceChildren(), and removing a parent.
It only runs for an element that was connected. Take a badge out of a box that isn't on the page, and nothing runs. It never joined, so it can't leave.
Now try it. The page has a Brewing shelf and a Ready shelf. Line 10 does one thing to the Oolong badge. Pick what it does:
<p id="brewing">Brewing: <tea-badge>Oolong</tea-badge></p><p id="ready">Ready: </p> <script src="tea-badge.js"></script> <script> const badge = document.querySelector("tea-badge"); const brewing = document.querySelector("#brewing"); const ready = document.querySelector("#ready"); ready.append(badge); console.log("Done");</script>disconnectedCallback() runs, then connectedCallback()The first line is the upgrade, when line 4 loads tea-badge.js. Then line 10 moves the badge. A move takes the badge out and puts it in again, so it leaves, then joins.
Two results surprise most people. Hiding the badge runs nothing. It's still on the page, just not drawn. And append() to the shelf it's already on runs both callbacks. The next section explains why.
Why does connectedCallback run more than once?
Because an element can join the page many times. When you append() an element that's already somewhere, the browser first takes it out of its old place. Then it puts it in the new one. The DOM Standard's steps for inserting a node do it in that order. Each step runs its callback.
Frameworks move elements too. When a list is sorted, a framework may move the same elements into a new order. Nolan Lawson points out that each move is a disconnect and a reconnect for your element.
So connectedCallback() must be safe to run again. Most work is. Setting textContent, as the kit's tea-label does, gives the same result every time. Adding something is different:
<p id="brewing">Brewing: <tea-order>Oolong</tea-order></p><p id="ready">Ready: </p> <script> class TeaOrder extends HTMLElement { connectedCallback() { const button = document.createElement("button"); button.textContent = "Serve"; this.append(" ", button); } } customElements.define("tea-order", TeaOrder); const order = document.querySelector("tea-order"); document.querySelector("#ready").append(order); console.log("Buttons:", order.querySelectorAll("button").length);</script>- Lines 6 to 10 add a Serve button each time the order joins the page.
- Line 12 registers the class. The order from line 1 is upgraded, and it gets its first button.
- Line 15 moves the order to Ready. It leaves, joins again, and gets a second button.
- Line 16 prints
Buttons: 2.
The HTML Standard warns about this. Work that must happen only once needs a guard: a check that skips it the second time.
<p id="brewing">Brewing: <tea-order>Oolong</tea-order></p><p id="ready">Ready: </p> <script> class TeaOrder extends HTMLElement { #built = false; connectedCallback() { if (this.#built) return; this.#built = true; const button = document.createElement("button"); button.textContent = "Serve"; this.append(" ", button); } } customElements.define("tea-order", TeaOrder); const order = document.querySelector("tea-order"); document.querySelector("#ready").append(order); console.log("Buttons:", order.querySelectorAll("button").length);</script>- Line 6 adds
#built, set tofalse. A name that starts with#is a private field. Only code inside the class can read it. - Line 9 is the guard. If the button was built before,
returnleaves the method at once. - Line 10 notes that the button is built now.
- Line 20 prints
Buttons: 1.
Every morning, Asha unlocks the shop and switches on the lights. She does it again the next day, and nothing goes wrong. But she painted the sign over the door only once. If she painted it every morning, the paint would pile up.
- In real life: Each new morning
- In JavaScript: Each time the element joins the page
- In real life: Unlocking the door and switching on the lights
- In JavaScript: Work that is safe to run every time
- In real life: Painting the sign over the door
- In JavaScript: One-time setup, like the Serve button
- In real life: The note that says the sign is done
- In JavaScript: The
#builtguard
Why it matters: without a guard, every move adds another copy. The page looks broken after the first sort.
Moving an element with moveBefore()
Sometimes a move shouldn't count as leaving at all. Newer browsers have moveBefore(), a method that moves an element in one step. It works like insertBefore(). ready.moveBefore(badge, null) puts the badge at the end of ready.
On its own, moveBefore() still runs both callbacks, so older components keep working. Your class can ask for something else. If it has a connectedMoveCallback() method, the browser calls only that one for the move. Even an empty one works.
<p id="brewing">Brewing: <tea-badge>Oolong</tea-badge></p><p id="ready">Ready: </p> <script src="tea-badge.js"></script> <script> const badge = document.querySelector("tea-badge"); const ready = document.querySelector("#ready"); if ("moveBefore" in Element.prototype) { ready.moveBefore(badge, null); } else { ready.append(badge); }</script>- Lines 8 to 10 of
tea-badge.js, the second tab, addconnectedMoveCallback(). - Line 9 of the page checks that this browser has
moveBefore(). It's the feature check from lesson 1.2. - Line 10 moves the badge to Ready. The console prints
Oolong joined the pagefrom the upgrade, thenOolong moved. - Line 12 is for Safari, which has no
moveBefore(). There, the badge leaves and joins again.
Take lines 8 to 10 out of tea-badge.js, and moveBefore() runs the other two callbacks again. Lesson 3.5, moving and adopting elements, goes deeper.
append() takes the badge out and puts it back, so two callbacks run. moveBefore() with a connectedMoveCallback() runs only that one.Here is everything the last three sections showed. Read each row across:
| What the code does | Which callbacks run |
|---|---|
p.append(badge), for a badge that isn't on the page yet. | connectedCallback() runs. |
box.append(badge), for a box that isn't on the page. | None. The badge isn't in a document. |
badge.remove() | disconnectedCallback() runs. |
p.textContent = "Sold out", with badges inside p. | disconnectedCallback() runs for each badge. |
ready.append(badge), for a badge already on the page. | disconnectedCallback() runs, then connectedCallback(). |
ready.moveBefore(badge, null), with a connectedMoveCallback(). | Only connectedMoveCallback() runs. |
ready.moveBefore(badge, null), without one. | disconnectedCallback() runs, then connectedCallback(). |
badge.hidden = true | None. A hidden badge is still on the page. |
How do you clean up in disconnectedCallback?
Back to Asha's ticking console. Ravi's timer starts a setInterval() in connectedCallback(). setInterval() runs a function again and again, here once a second. It belongs to the window, not to the element. So it keeps going after the element leaves.
Try both versions of the timer. Press Brew, wait two ticks, then press Serve:
<p id="shelf">Green tea: </p><button id="brew">Brew</button><button id="serve">Serve</button> <script src="tea-timer.js"></script> <script> const timer = document.createElement("tea-timer"); const shelf = document.querySelector("#shelf"); document.querySelector("#brew").onclick = () => shelf.append(timer); document.querySelector("#serve").onclick = () => timer.remove();</script>Press Brew, wait two ticks, then press Serve. The timer leaves the page, but nothing stops its setInterval(). It keeps ticking for a timer nobody can see.
- Line 2 of the fixed
tea-timer.jsadds a private field,#interval. - Line 7 keeps the number that
setInterval()gives back. That number names this timer. - Lines 14 to 16 are
disconnectedCallback(). Line 15 passes the number toclearInterval(), which stops the timer.
With Ravi's first version, the ticks go on after Serve: Tick: 3 s, then Tick: 4 s. With the fixed one, they stop at Tick: 2 s. Press Brew again, and a new count starts from 0.
Memory is the second reason. Lit's docs say that disconnectedCallback() should make sure nothing outside still holds on to the element. Otherwise the browser can't free it.
Removing outside listeners with AbortController
A listener on document or window keeps going too, because the document is still there. Lit's docs name this as the most common job for the two callbacks: add outside listeners when the element joins, and remove them when it leaves.
You could remove each one with removeEventListener(). But that needs the exact same function you added, saved somewhere. An AbortController is simpler. It's an object with a signal and an abort() method. Pass the signal when you add a listener. Later, one call to abort() removes every listener that got that signal.
Ravi's shop shows a tip that closes when you click anywhere, or press any key. Click the page twice:
<p>Teas: Green, Oolong, Black</p><tea-tip>Tip: brew green tea at 80°C. Click anywhere to close.</tea-tip> <script src="tea-tip.js"></script>The page only shows the tip. Its class is in tea-tip.js, the second tab:
- Line 5 makes a new controller each time the tip joins the page.
- Line 6 takes its signal.
- Lines 7 and 8 add two listeners on the document. Both get the same signal, in
{ signal }. - Line 12, in
disconnectedCallback(), callsabort(). Both listeners are gone. - Lines 15 to 18 print
Closing the tipand remove the tip.
The first click prints Closing the tip, and the tip disappears. Its disconnectedCallback() runs and aborts. The second click prints nothing. Without lines 11 to 13, the second click prints Closing the tip again, for a tip that's already gone.
abort() removes both.Ravi's market stall has a lamp, a fan, and a radio, all plugged into one power strip. At closing time, he doesn't hunt for each plug. He flips the switch on the strip, and everything goes off at once.
- In real life: The power strip
- In JavaScript: The
AbortController - In real life: Plugging a lamp into the strip
- In JavaScript: Passing
{ signal }toaddEventListener() - In real life: The lamp and the fan
- In JavaScript: The click and keydown listeners
- In real life: Flipping the strip's switch
- In JavaScript:
abort()
A new controller each time
Line 5 of tea-tip.js is inside connectedCallback(), not the constructor. That matters, because a signal stays aborted for good. addEventListener() skips a listener whose signal is already aborted:
const controller = new AbortController();
controller.abort();
document.addEventListener("click", () => console.log("Click"), {
signal: controller.signal,
});
document.dispatchEvent(new Event("click"));
console.log("Aborted:", controller.signal.aborted);- Lines 1 and 2 make a controller and abort it.
- Lines 4 to 6 add a click listener with the aborted signal.
- Line 7 sends a click to the document. Nothing prints.
- Line 8 prints
Aborted: true.
So a controller made once, in the constructor, works only until the element first leaves. When the element comes back, its listeners are never added. Nolan Lawson describes the same trap: setup in the constructor, cleanup in disconnectedCallback(). Make a new controller each time the element joins. Exercise 4 has this bug.
A signal can stop more than listeners. signal.addEventListener("abort", …) runs a function when you abort. The kit's timer uses it to clear its interval, at the end of this lesson.
For more on signals, see Cancellation with AbortController. Now sort these lines. Which ones does disconnectedCallback() need to stop?
setInterval(…)document.addEventListener("click", …)window.addEventListener("resize", …)this.addEventListener("click", …)- A click listener on a button inside the element
this.textContent = "Ready"
Sort each line from a connectedCallback() by whether it needs cleanup when the element leaves.
In what order do parents and children connect?
A shelf with two cups inside joins the page. That's three elements joining at once. Whose callback runs first? Here is a shelf that leaves and comes back:
<tea-shelf id="shelf"> <tea-cup id="cup-1"></tea-cup> <tea-cup id="cup-2"></tea-cup></tea-shelf> <script src="callbacks.js"></script> <script> const shelf = document.querySelector("tea-shelf"); shelf.remove(); console.log("remove() is done"); document.body.append(shelf); console.log("append() is done");</script>- Lines 1 to 4 put a shelf with two cups on the page.
callbacks.js, the second tab, gives both tags the same two callbacks. They print the element'sid. - Line 6 loads
callbacks.js. Each element is upgraded and printsjoined: the shelf, thencup-1, thencup-2. - Line 10 removes the shelf. The shelf,
cup-1, andcup-2printleft, in that order. Then line 11 printsremove() is done. - Line 12 puts the shelf back. The three join in the same order, and line 13 prints
append() is done.
Two rules show here.
First, the order is the order of the page, from top to bottom. The parent comes first, then its children. The DOM Standard calls it tree order, and it uses it both when elements join and when they leave.
Second, all the callbacks ran before the next line of the script. The HTML Standard calls them custom element reactions. While append() changes the page, the browser doesn't stop to run your code. It puts each callback in a queue. Just before append() returns to your script, it runs the queue, in order. For most code, it looks as if each callback ran at once.
append() returns, so append() is done prints fourth. Leaving goes in the same order.A family of three walks into the tea shop. The host doesn't stop them in the doorway to greet each one. She waits until all three are inside. Then she greets the parent, then each child in turn. Only then does she show them to a table.
- In real life: The family walking in together
- In JavaScript: A shelf joining the page with its cups
- In real life: The host's list of names
- In JavaScript: The queue of callbacks
- In real life: Greeting the parent, then each child
- In JavaScript: The shelf's callback, then
cup-1's, thencup-2's - In real life: Showing them to a table
- In JavaScript: Your script's next line
The standard makes one more promise. Each element's own callbacks run in the order its changes happened. Across different elements, there's no fixed promise, because your callbacks can change the page too. Lesson 3.6, the custom element lifecycle in order, steps through the full timing.
Why can isConnected be false in connectedCallback?
Because the queue can fall behind. A callback is queued when the element joins. If something removes the element before the queue gets to it, the callback still runs. The HTML Standard warns about this case. Here is a tray that clears away its cup as soon as it's put down:
<p>Tray: </p> <script> class TeaCup extends HTMLElement { connectedCallback() { console.log("Cup joined. isConnected:", this.isConnected); } } class TeaTray extends HTMLElement { connectedCallback() { this.querySelector("tea-cup").remove(); } } customElements.define("tea-cup", TeaCup); customElements.define("tea-tray", TeaTray); const tray = document.createElement("tea-tray"); tray.append(document.createElement("tea-cup")); document.querySelector("p").append(tray);</script>- Lines 4 to 8 are the cup. Its
connectedCallback()printsisConnected. - Lines 9 to 13 are the tray. Its
connectedCallback()removes the cup inside it. - Lines 17 and 18 make a tray with a cup.
- Line 19 puts the tray on the page. Both elements join, so two callbacks are queued: the tray's, then the cup's.
The tray's callback runs first and removes the cup. Then the cup's callback runs, as queued. It prints Cup joined. isConnected: false. The cup was on the page when its callback was queued. It had left by the time the callback ran.
A guest at table 4 orders a pot of oolong. While it brews, she gets up and leaves. The waiter carries the pot over anyway. She looks at the seat before she pours. It's empty, so she takes the tea back.
- In real life: Carrying over the tea someone ordered
- In JavaScript: A queued callback, or work after an
await - In real life: The guest who left while it brewed
- In JavaScript: An element removed in the meantime
- In real life: Looking at the seat first
- In JavaScript:
if (!this.isConnected) return;
So when connectedCallback() does work that only makes sense on the page, check first: if (!this.isConnected) return;. The HTML Standard also asks callbacks not to change the page around them, as the tray did. It leads to surprises like this one.
An async connectedCallback
The same check matters after an await. You can write async connectedCallback() and wait for data inside it. The browser calls it like any other method. Nolan Lawson points out that the browser ignores the promise it gives back. It doesn't wait. By the time the data arrives, the element may have left:
<p>Menu: </p> <script> class TeaMenu extends HTMLElement { async connectedCallback() { await new Promise((done) => setTimeout(done, 300)); if (!this.isConnected) { console.log("Gone before the menu loaded"); return; } this.textContent = "Green, Oolong, Black"; } } customElements.define("tea-menu", TeaMenu); const menu = document.createElement("tea-menu"); document.querySelector("p").append(menu); console.log("append() is done"); menu.remove();</script>- Line 5 makes the callback
async. - Line 6 waits 300 ms. It stands in for loading the menu from a server.
- Lines 7 to 10 check
isConnectedafter the wait. They stop if the menu has left. - Line 17 adds the menu, and its callback starts. Line 18 prints
append() is doneat once. - Line 19 removes the menu before the wait is over.
A moment later, the console prints Gone before the menu loaded. Without lines 7 to 10, the menu would fill itself in while off the page. In a real component, that might be a listener added after the element left. Nothing would ever remove it.
Adding a brewing timer to the tea kit
Ravi adds the timer to the tea kit, so every page can use it. The kit's timer counts down from its seconds attribute and shows Ready at 0. It uses everything from this lesson. Press Brew, then move it both ways:
<script type="importmap"> { "imports": { "tea-kit/": "./tea-kit/" } }</script> <p id="brewing">Brewing: </p><p id="ready">Ready: </p><button id="brew">Brew</button><button id="append">Move with append()</button><button id="move">Move with moveBefore()</button> <script type="module"> import "tea-kit/index.js"; const timer = document.createElement("tea-timer"); timer.setAttribute("seconds", "5"); const [brewing, ready] = document.querySelectorAll("p"); const other = () => (timer.parentNode === brewing ? ready : brewing); document.querySelector("#brew").onclick = () => brewing.append(timer); document.querySelector("#append").onclick = () => other().append(timer); document.querySelector("#move").onclick = () => other().moveBefore(timer, null); document.querySelector("#move").disabled = !("moveBefore" in Element.prototype);</script>- Lines 1 to 3 are the import map from lesson 1.4. Line 12 loads the whole kit, now with
tea-timer.js. - Lines 14 and 15 make a timer by name and give it 5 seconds.
- Line 18 adds it to Brewing. Lines 19 and 20 move it to the other shelf, with
append()ormoveBefore(). - Line 21 turns off the
moveBefore()button in browsers that don't have it.
Now open the tea-kit/tea-timer.js tab:
- Line 5 makes a new
AbortControllereach time the timer joins. - Line 6 reads
secondshere, not in the constructor, as lesson 3.2 taught. - Lines 8 to 12 count down once a second and stop at Ready.
- Line 13 clears the interval when the signal aborts.
- Line 17 aborts in
disconnectedCallback(). - Line 20 is an empty
connectedMoveCallback().
Press Brew and wait two seconds: the timer shows 3 s. Move it with append(). It leaves and joins, so it starts again at 5 s. Wait a second, then move it with moveBefore(). It stays at 4 s and keeps counting. The empty connectedMoveCallback() tells Chrome and Firefox that a move isn't a reset. In Safari, that button is off.
The kit's first files from lesson 3.1 stay as they are. They only set textContent, which is safe to repeat. The kit gains three rules:
- Whatever
connectedCallback()starts,disconnectedCallback()stops. - Each connection gets a new
AbortController, and one signal stops its listeners and timers. - Setup that must happen only once gets a guard.
Asha puts the kit's timer in her shop. Now, when she serves a tea, its timer stops ticking.
Common mix-ups
- "
connectedCallback()runs once, like the constructor." No. It runs each time the element joins the page. Every move runs it again. - "
disconnectedCallback()means the element is gone for good." No. It can come back. Undo everything, and expectconnectedCallback()to set it up again. - "Set things up in the constructor, and clean up in
disconnectedCallback()." No. The constructor runs once. After the first trip off the page, the cleanup has run, and the setup never comes back. - "Hiding an element runs
disconnectedCallback()." No. A hidden element is still in the document. Only leaving it counts. - "One
AbortController, made in the constructor, is enough." No. After the firstabort(), its signal stays aborted. Listeners added with it later are skipped. - "An
async connectedCallback()makes the browser wait." No. The browser ignores the promise. The element can leave before yourawaitis over. - "Every listener needs removing." No. Listeners on the element itself, or on elements inside it, go away with it. Only outside ones need cleanup.
- "Inside
connectedCallback(),isConnectedis always true." No. A queued callback can run after the element has left.
Practice exercises
Answer first, then use the hints. The solutions run live, so you can check yourself.
How many times does the console print Organic joined the page?
<p id="a">A: </p>
<p id="b">B: </p>
<script>
class TeaBadge extends HTMLElement {
connectedCallback() {
console.log(`${this.textContent} joined the page`);
}
disconnectedCallback() {
console.log(`${this.textContent} left the page`);
}
}
customElements.define("tea-badge", TeaBadge);
const badge = document.createElement("tea-badge");
badge.textContent = "Organic";
const box = document.createElement("div");
box.append(badge);
document.querySelector("#a").append(box);
document.querySelector("#b").append(box);
badge.remove();
</script><p id="a">A: </p><p id="b">B: </p> <script> class TeaBadge extends HTMLElement { connectedCallback() { console.log(`${this.textContent} joined the page`); } disconnectedCallback() { console.log(`${this.textContent} left the page`); } } customElements.define("tea-badge", TeaBadge); const badge = document.createElement("tea-badge"); badge.textContent = "Organic"; const box = document.createElement("div"); box.append(badge); document.querySelector("#a").append(box); document.querySelector("#b").append(box); badge.remove();</script>Twice. Line 18 puts the badge in a box off the page, so nothing runs. Line 19 puts the box on the page: joined. Line 20 moves the box, and the badge inside leaves and joins again. Line 21 removes it: left.
What does the console print last?
<tea-shelf id="top">
<tea-cup id="green"></tea-cup>
</tea-shelf>
<tea-shelf id="bottom">
<tea-cup id="black"></tea-cup>
</tea-shelf>
<script>
class Logged extends HTMLElement {
connectedCallback() { console.log(`${this.id} joined`); }
disconnectedCallback() { console.log(`${this.id} left`); }
}
customElements.define("tea-shelf", class extends Logged {});
customElements.define("tea-cup", class extends Logged {});
const bottom = document.querySelector("#bottom");
document.querySelector("#top").append(bottom);
</script><tea-shelf id="top"> <tea-cup id="green"></tea-cup></tea-shelf><tea-shelf id="bottom"> <tea-cup id="black"></tea-cup></tea-shelf> <script> class Logged extends HTMLElement { connectedCallback() { console.log(`${this.id} joined`); } disconnectedCallback() { console.log(`${this.id} left`); } } customElements.define("tea-shelf", class extends Logged {}); customElements.define("tea-cup", class extends Logged {}); const bottom = document.querySelector("#bottom"); document.querySelector("#top").append(bottom);</script>black joined. The move runs bottom left, bottom joined, black left, black joined. The browser runs each element's queued callbacks together, the shelf's first, then the cup's.
What does line 16 print? Then fix the class so the note is added only once.
<p id="new">New: <tea-note>Oolong</tea-note></p><p id="all">All teas: </p> <script> class TeaNote extends HTMLElement { connectedCallback() { const small = document.createElement("small"); small.textContent = " (new)"; this.append(small); } } customElements.define("tea-note", TeaNote); const note = document.querySelector("tea-note"); document.querySelector("#all").append(note); console.log(note.textContent);</script><p id="new">New: <tea-note>Oolong</tea-note></p><p id="all">All teas: </p> <script> class TeaNote extends HTMLElement { #added = false; connectedCallback() { if (this.#added) return; this.#added = true; const small = document.createElement("small"); small.textContent = " (new)"; this.append(small); } } customElements.define("tea-note", TeaNote); const note = document.querySelector("tea-note"); document.querySelector("#all").append(note); console.log(note.textContent);</script>It prints Oolong (new) (new): the upgrade adds one note and the move adds another. The guard on line 9 skips the second time, so the fixed page prints Oolong (new).
Click the page once. What does the console print? Then fix it.
<p>Click anywhere on this page.</p><tea-tip>Tip: brew green tea at 80°C.</tea-tip> <script> class TeaTip extends HTMLElement { #controller = new AbortController(); connectedCallback() { const signal = this.#controller.signal; document.addEventListener("click", () => console.log("Tip heard a click"), { signal }); } disconnectedCallback() { this.#controller.abort(); } } customElements.define("tea-tip", TeaTip); const tip = document.querySelector("tea-tip"); tip.remove(); document.body.append(tip);</script><p>Click anywhere on this page.</p><tea-tip>Tip: brew green tea at 80°C.</tea-tip> <script> class TeaTip extends HTMLElement { #controller; connectedCallback() { this.#controller = new AbortController(); const signal = this.#controller.signal; document.addEventListener("click", () => console.log("Tip heard a click"), { signal }); } disconnectedCallback() { this.#controller.abort(); } } customElements.define("tea-tip", TeaTip); const tip = document.querySelector("tea-tip"); tip.remove(); document.body.append(tip);</script>Nothing. Line 20 removes the tip, which aborts the only controller. When line 21 adds the tip back, its listener has an aborted signal, so it's never added. With a new controller in connectedCallback(), a click prints Tip heard a click.
Follow the steps in the comments. Then press Brew, wait two seconds, and press Serve. How many Tick lines print after Serve?
<p id="shelf">Green tea: </p><button id="brew">Brew</button><button id="serve">Serve</button> <script> class TeaTimer extends HTMLElement { // 1. Add a #controller field. connectedCallback() { // 2. Make a new AbortController here. let seconds = 0; const interval = setInterval(() => { seconds += 1; console.log(`Tick: ${seconds} s`); }, 1000); // 3. Clear the interval when the signal aborts. } // 4. Abort the controller in disconnectedCallback(). } customElements.define("tea-timer", TeaTimer); const timer = document.createElement("tea-timer"); const shelf = document.querySelector("#shelf"); document.querySelector("#brew").onclick = () => shelf.append(timer); document.querySelector("#serve").onclick = () => timer.remove();</script><p id="shelf">Green tea: </p><button id="brew">Brew</button><button id="serve">Serve</button> <script> class TeaTimer extends HTMLElement { #controller; connectedCallback() { this.#controller = new AbortController(); let seconds = 0; const interval = setInterval(() => { seconds += 1; console.log(`Tick: ${seconds} s`); }, 1000); this.#controller.signal.addEventListener("abort", () => clearInterval(interval)); } disconnectedCallback() { this.#controller.abort(); } } customElements.define("tea-timer", TeaTimer); const timer = document.createElement("tea-timer"); const shelf = document.querySelector("#shelf"); document.querySelector("#brew").onclick = () => shelf.append(timer); document.querySelector("#serve").onclick = () => timer.remove();</script>None. Serve removes the timer, disconnectedCallback() aborts, and the signal's abort event clears the interval. The starter keeps printing ticks after Serve.
Click the page once. How many lines does the console print? Then make it print one.
<p id="a">A: <tea-tip>Tip: brew green tea at 80°C.</tea-tip></p><p id="b">B: </p> <script> class TeaTip extends HTMLElement { connectedCallback() { document.addEventListener("click", () => console.log("Tip heard a click")); } } customElements.define("tea-tip", TeaTip); const tip = document.querySelector("tea-tip"); document.querySelector("#b").append(tip); document.querySelector("#a").append(tip);</script><p id="a">A: <tea-tip>Tip: brew green tea at 80°C.</tea-tip></p><p id="b">B: </p> <script> class TeaTip extends HTMLElement { #controller; connectedCallback() { this.#controller = new AbortController(); const signal = this.#controller.signal; document.addEventListener("click", () => console.log("Tip heard a click"), { signal }); } disconnectedCallback() { this.#controller.abort(); } } customElements.define("tea-tip", TeaTip); const tip = document.querySelector("tea-tip"); document.querySelector("#b").append(tip); document.querySelector("#a").append(tip);</script>Three. The tip joins three times, so the document gets three listeners. With one controller per connection, each move aborts the old listener, and one click prints one line.
Check your understanding
For each question, ask when the element joined, when it left, and what is still running.
Question 1 of 8When does the browser call an element's
connectedCallback()?Choose an answer to see the explanation.
Question 2 of 8What does this page print, from lines 12 and 13?
Read the code, then predict<p>Teas: </p> <script> class TeaBadge extends HTMLElement { connectedCallback() { console.log("joined"); } disconnectedCallback() { console.log("left"); } } customElements.define("tea-badge", TeaBadge); const badge = document.createElement("tea-badge"); const p = document.querySelector("p"); p.append(badge); p.append(badge); </script>Choose an answer to see the explanation.
Question 3 of 8Which line belongs in
disconnectedCallback()?Choose an answer to see the explanation.
Question 4 of 8Why does
connectedCallback()make a newAbortControllereach time?Choose an answer to see the explanation.
Question 5 of 8A tray's
connectedCallback()removes its cup. Then the cup'sconnectedCallback()printsthis.isConnected. What does it print, and why?Choose an answer to see the explanation.
Question 6 of 8You add a shelf that holds two cups. In what order do the three
connectedCallback()calls run?Choose an answer to see the explanation.
Question 7 of 8An element has a
connectedMoveCallback(). You move it withmoveBefore(). Which callbacks run?Choose an answer to see the explanation.
Question 8 of 8What happens when
connectedCallback()isasyncand awaits some data?Choose an answer to see the explanation.
Key takeaways
connectedCallback()runs each time the element joins a document.disconnectedCallback()runs each time it leaves.- A parent off the page isn't enough.
isConnectedtells you whether the element is in a document. - A move with
append()runs both callbacks. A move withmoveBefore()runs onlyconnectedMoveCallback(), if the class has one. - Setup that must happen once needs a guard, because the callbacks run many times.
- Stop timers and remove outside listeners when the element leaves. One
AbortControllerper connection does both. - Callbacks are queued: the parent first, then its children in page order, all before the DOM method returns. Check
isConnectedwhen work might come too late.
Remember the one-liner.
Start it when the element joins the page, stop it when it leaves, and expect both to happen many times.
Sources
The facts on this page come from these standards and docs:
- Using custom elements: Custom element lifecycle callbacks, MDN.
- HTML Standard: Requirements for custom element constructors and reactions, WHATWG.
- Node: isConnected property, MDN.
- DOM Standard: Insert, WHATWG.
- DOM Standard: Remove, WHATWG.
- HTML Standard: Preserving custom element state when moved, WHATWG.
- DOM Standard: Move, WHATWG.
- Element: moveBefore() method, MDN.
- AbortController, MDN.
- EventTarget: addEventListener(), Add an abortable listener, MDN.
- Lifecycle, Lit.
- Web component gotcha: constructor vs connectedCallback, Nolan Lawson.
- HTML Standard: Custom element reactions, WHATWG.
- Is it okay to make connectedCallback async?, Nolan Lawson.
- Modern Web Guidance: Custom elements, Chrome for Developers.
Coming next: Reacting to attributes. List the attributes you care about, and react when they change.