The custom element lifecycle in order
Learn the web component lifecycle: the order of every custom element callback, what each one can see, and how to wait for children in connectedCallback.
- 01Name every callback in orderThe constructor,
attributeChangedCallback(),connectedCallback(), and then moves, adoptions, anddisconnectedCallback(). - 02Predict what each callback can seeAttributes, children,
isConnected, and the parent, for the parser,createElement(),innerHTML, an upgrade, and copies. - 03Read children safelyWatch them with a
MutationObserverorslotchange, wait for the page to be parsed, and know why timers aren't enough.
What is the custom element lifecycle?
Ravi made a tag for the menus at Leaf and Kettle, called tea-menu. It counts the teas inside it and writes the count at the top: "3 teas on the menu". On his test page, it works.
Asha puts it on the shop's page. There it says "0 teas on the menu", right above three teas. It's the same class and the same menu. Why does one page count 3, and the other 0?
The web component lifecycle is the set of methods the browser calls on a custom element as it lives on the page. They always run in the same order: the constructor, then attributeChangedCallback() for each attribute it watches, then connectedCallback() when it joins the page, and disconnectedCallback() when it leaves. The order never changes. What changes is what the element already has when each one runs.
Here are both pages. They load the same tea-menu.js, in the second tab:
<script src="tea-menu.js"></script> <tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p></tea-menu><tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p></tea-menu> <script src="tea-menu.js"></script>- In
tea-menu.js, line 3 counts the menu's children.childrenholds the elements inside it: here, the three<p>teas. - Line 4 prints the count. Line 5 writes it at the top of the menu with
prepend(). - Asha's page loads the class on line 1, before the menu. It prints
Counted 0 teas. - Ravi's page loads it on line 7, after the menu. It prints
Counted 3 teas.
The browser reads a page from top to bottom. That reading is called parsing, and the part of the browser that does it is the parser. On Asha's page, the parser already knows the class when it reaches <tea-menu>. It makes the menu, puts it on the page, and calls connectedCallback() right there. Only then does it read the teas.
On Ravi's page, the menu and its teas are all in place when the class loads. The menu is upgraded: a tag that waited on the page gets its class at last. Lesson 3.2, What the constructor may do, showed upgrades. Here the menu finds all three teas.
connectedCallback() runs at the opening tag, before the teas exist. With the class loaded last, define() upgrades a menu that already has them.At Leaf and Kettle, a ticket prints in the kitchen the moment a table orders. A new cook counts the plates on the counter as soon as the ticket prints. There are none yet. The dishes come out one by one, after the ticket.
- In real life: The ticket printing in the kitchen
- In JavaScript:
connectedCallback()running at the opening tag - In real life: The dishes coming out, one by one
- In JavaScript: The parser adding the teas after it
- In real life: Counting the plates when the ticket prints
- In JavaScript:
this.children.lengthinconnectedCallback() - In real life: A cook who starts after the dishes are out
- In JavaScript: An upgrade: the class loads after the HTML
The lifecycle callbacks always run in the same order. What each one can see depends on how the element was made. When the parser builds an element whose class is already loaded, connectedCallback() runs at the opening tag, before any children exist.
In what order do the lifecycle callbacks run?
Lessons 3.2 to 3.5 met each callback on its own. Here is one menu's whole life, so you can see them all in a row. This tea-menu.js has all six callbacks, and each one prints its name:
<p id="shelf">Shelf:</p><p id="featured">Featured:</p><template id="storeroom"></template> <script src="tea-menu.js"></script> <script> const shelf = document.querySelector("#shelf"); const storeroom = document.querySelector("#storeroom").content; const menu = document.createElement("tea-menu"); menu.setAttribute("name", "Winter"); shelf.append(menu); menu.setAttribute("name", "Spring"); document.querySelector("#featured").moveBefore?.(menu, null); storeroom.append(menu); shelf.append(menu); menu.remove();</script>- In
tea-menu.js, the second tab, line 2 asks to hear about thenameattribute. Lines 4 to 22 print each callback's name.attributeChangedCallback()also prints the old and new values. - On the page, line 3 is a
<template>, a storeroom off the page. Line 9 takes itscontent. - Line 10 makes the menu. Line 11 names it Winter. Line 12 adds it to the shelf.
- Line 13 renames it Spring.
- Line 14 moves it to Featured with
moveBefore(). The?.skips the call in browsers without it, like Safari. - Line 15 puts it in the storeroom. Line 16 brings it back. Line 17 removes it.
The console prints ten lines. Each line of the script runs its own callbacks, in order:
Put together, every custom element's life follows these rules:
- The constructor runs once, first, when the element is made or upgraded. See lesson 3.2.
attributeChangedCallback()runs for each watched attribute the element already has, right after the constructor. After that, it runs whenever one changes. See lesson 3.4, Reacting to attributes.connectedCallback()runs each time the element joins a document.disconnectedCallback()runs each time it leaves. See lesson 3.3, connectedCallback and disconnectedCallback.- A move with
append()runsdisconnectedCallback(), thenconnectedCallback(). A move withmoveBefore()runs onlyconnectedMoveCallback(), if the class has one. - A trip into another document runs
disconnectedCallback(),adoptedCallback(), thenconnectedCallback(). See lesson 3.5, Moving and adopting elements.
Two more rules come from lesson 3.3. When a parent and its children join together, the parent's callbacks run first, then each child's, from top to bottom. And the browser doesn't stop in the middle of changing the page to run your code. It queues each callback, then runs the queue just before the DOM method returns. The HTML Standard calls these queued calls custom element reactions. So each callback seems to run inside the line that caused it.
In lesson 3.2, a potter shaped a teapot. Its day in the shop always goes the same way. A label is tied on. It's set on a table. It may slide to the next table, or go to the café next door for a while. At closing time, it's cleared away. The label can change at any time.
- In real life: Shaping the pot
- In JavaScript: The constructor
- In real life: Tying on its label
- In JavaScript:
attributeChangedCallback() - In real life: Setting it on a table
- In JavaScript:
connectedCallback() - In real life: Sliding it to the next table
- In JavaScript:
connectedMoveCallback() - In real life: Lending it to the café next door
- In JavaScript:
adoptedCallback() - In real life: Clearing it away
- In JavaScript:
disconnectedCallback()
Why it matters: put each job in the callback whose moment fits it. Setup that needs the page goes in connectedCallback(). Cleanup goes in disconnectedCallback().
What can each lifecycle callback see?
The order is fixed. But a callback doesn't always see the same element. Sometimes the attributes are there, and sometimes not. Sometimes the teas are inside, and sometimes not. It depends on how the menu was made.
This tea-menu.js reports four things at each of the first three callbacks: the name attribute, the number of teas, isConnected, and the parent. Pick a way to make the menu:
<script src="tea-menu.js"></script> <div id="board"> <tea-menu name="Winter"> <p>Oolong</p> <p>Green</p> <p>Black</p> </tea-menu></div>The parser knows the class when it reads <tea-menu>. It runs all three callbacks right there, before it reads the teas. So connectedCallback() counts 0.
- In
tea-menu.js, line 2 watches thenameattribute. - Lines 6, 10, and 14 call
report()from the constructor and the two callbacks. - Line 19 reads the name. It's
nullwhen the attribute isn't there yet. - Line 20 counts the teas. Line 21 reads the parent's tag name, or
none. - Line 22 prints it all, with
isConnected. That'struewhile the menu is in a document.
Reading attributes and children in a constructor breaks a rule from lesson 3.2. This file does it only to show you what's there.
Here is what each way printed in Chrome. Read each row across. Each cell says when the callback ran, then what it saw:
| How the menu is made | constructor() | attributeChangedCallback() | connectedCallback() |
|---|---|---|---|
| The parser, with the class loaded first | At the opening tag. name null, teas 0, connected false, parent none | At the opening tag. name Winter, teas 0, connected false, parent none | At the opening tag. name Winter, teas 0, connected true, parent DIV |
| An upgrade, with the class loaded after the HTML | Inside define(). name Winter, teas 3, connected true, parent DIV | Inside define(). name Winter, teas 3, connected true, parent DIV | Inside define(). name Winter, teas 3, connected true, parent DIV |
createElement(), then append() | Inside createElement(). name null, teas 0, connected false, parent none | Inside setAttribute(). name Winter, teas 0, connected false, parent none | Inside append(). name Winter, teas 3, connected true, parent DIV |
innerHTML | As the innerHTML line ends. name Winter, teas 3, connected true, parent DIV | As the innerHTML line ends. name Winter, teas 3, connected true, parent DIV | As the innerHTML line ends. name Winter, teas 3, connected true, parent DIV |
cloneNode(true), then append() | Inside cloneNode(). name Winter, teas 3, connected false, parent none | Inside cloneNode(). name Winter, teas 3, connected false, parent none | Inside append(). name Winter, teas 3, connected true, parent DIV |
| A template's content, copied and added | Inside append(). name Winter, teas 3, connected true, parent DIV | Inside append(). name Winter, teas 3, connected true, parent DIV | Inside append(). name Winter, teas 3, connected true, parent DIV |
Three things stand out:
- Only one way runs
connectedCallback()before the teas exist: the parser, with the class loaded first. WithcreateElement(), it depends on your script. Here, the teas went in beforeappend(). - In four ways, the constructor runs on a menu that already has its name and its teas: an upgrade,
innerHTML, and both kinds of copy. That's the trap from lesson 3.2. - Callbacks can run off the page.
isConnectedisfalsein the first two callbacks of the parser,createElement(), andcloneNode()rows.
Copies made with cloneNode()
cloneNode(true) copies an element with everything inside it. The true means children too. The copy is a new element, so it gets its own constructor. The DOM Standard's steps for cloning build it the way innerHTML builds elements: first a plain element, then its attributes and children, then the upgrade.
cloneNode() runs that upgrade before it returns. So the copy's constructor sees the name and all three teas, while isConnected is still false and it has no parent. Only connectedCallback() waits for append().
Chrome's source has both paths side by side, in CustomElementDefinition::CreateElement(). One path runs your class at once. The other makes a plain element and queues an upgrade.
Copies of a template
A <template> holds HTML that isn't on the page. Its content belongs to a separate document, as lesson 3.5 showed, and no classes are defined there. So template.content.cloneNode(true) makes a copy of plain elements. Nothing runs between Copying the template and Adding the copy. The copy upgrades inside append(), once it's on the page.
MDN warns about this, and suggests document.importNode(template.content, true) instead. That copies into the page's own document, which knows the class. Try it on line 16 of the template page. The constructor and the attribute callback then run inside importNode(), with connected false. Their parent is #document-fragment: the copied content.
Ravi takes three photos of every new shelf: when it's built, when its sign goes up, and when it's set in the shop. A shelf built in the shop looks empty in the first photos. A shelf delivered already full shows its teas in all three. The photos always come in the same order. What's in them depends on when the teas arrived.
- In real life: The three photos, always in that order
- In JavaScript: The constructor,
attributeChangedCallback(), andconnectedCallback() - In real life: The shelf's sign
- In JavaScript: The
nameattribute - In real life: A shelf built in the shop
- In JavaScript: The parser with the class loaded first, or
createElement() - In real life: A shelf delivered already full
- In JavaScript: An upgrade,
innerHTML, or a copy
Why it matters: you don't choose how people make your component. Write it so it works in all six rows.
Why are children missing in connectedCallback?
Asha's page is the row where the count goes wrong: the parser, with the class loaded first. It isn't a bug. The HTML Standard spells it out, step by step. Here is what the parser does when it reads <tea-menu name="Winter"> and the class is already defined:
- It looks up the tag and finds a class, so it knows it will run your code. The standard calls this step create an element for a token. A token is one tag the parser has read.
- It runs the constructor straight away. The menu has no attributes and no children.
- It adds the tag's attributes. That queues
attributeChangedCallback()forname, and the parser runs the queue at once. The menu still isn't on the page. - It puts the menu into its parent, in a step called insert an element at the adjusted insertion location. First it pushes a fresh, empty queue onto the custom element reactions stack, a pile of queues. Inserting queues
connectedCallback(). Right after, it takes that queue off the pile and runs it. - Only then does it read the next tag,
<p>Oolong</p>, and put it inside the menu.
So connectedCallback() runs while the parser is still on the opening tag. The teas are further down the page, and the parser hasn't read them yet. It's like counting the guests at a table the moment the booking is made.
This was decided on purpose. In 2016, a web developer reported that Chrome's connectedCallback() saw one child in a page like this. The people who write the standards talked it over in issue 551, and chose zero children for this case. Anne van Kesteren, an editor of the DOM Standard, gave the reason: "you should not depend on children, since you cannot depend on them with createElement() either."
Children can also change at any moment later, from a script. So there's no moment when a menu's children are final, and no callback that says "all my children are here". Issue 809, opened in 2019, asks for one. It hasn't been added.
Children that are components too
Sometimes the children exist, but they aren't ready. Say the menu holds tea-item elements with a class of their own. With innerHTML or an upgrade, the parent's callbacks run first. So when the menu connects, its items are still plain elements:
<div id="board"></div> <script src="tea-menu.js"></script> <script> document.querySelector("#board").innerHTML = ` <tea-menu> <tea-item>Oolong</tea-item> <tea-item>Green</tea-item> </tea-menu>`;</script>- Lines 1 to 6 of
tea-menu.js, the second tab, are the menu. Line 4 prints how many items it has, and whether the first one is ready. :definedmatches a custom element once its class has run on it. Lesson 2.4 used it in CSS.- Lines 8 to 12 are the item. Line 10 prints when each item connects.
- Lines 6 to 10 of the page build the menu with
innerHTML. Both classes are defined before this line runs.
The console prints Menu: 2 items, first ready: false, then Item ready: Oolong and Item ready: Green. The items are there, but their class hasn't run yet. So the menu can't use an item's methods or getters in its own connectedCallback(). Exercise 5 has this bug.
Why it matters: never treat the children as setup data that's ready when the parent connects. They may be missing, or not ready.
How do you wait for a custom element's children?
There's no callback for "my children are here". But there are four good ways to read them anyway, and one that only looks good. They all use the same page: the class loads first, and a button adds a tea. Only tea-menu.js changes.
Watching the children with a MutationObserver
A MutationObserver calls a function each time part of the page changes. The Observers lesson covers it in full. Here it watches the menu's own children:
<script src="tea-menu.js"></script> <tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p></tea-menu><button>Add a tea</button> <script> const menu = document.querySelector("tea-menu"); document.querySelector("button").onclick = () => { menu.insertAdjacentHTML("beforeend", "<p>Chai</p>"); };</script>- Line 3 of
tea-menu.jscounts once, at connect. That covers an upgrade, where the teas are already there. - Line 4 makes an observer and starts it.
childList: truemeans "tell me when children are added or removed". - Line 8 prints the count each time.
- On the page, lines 12 to 14 add a Chai each time you press the button.
The console prints Counted 0 teas, then Counted 3 teas. The observer ran once the parser had added the teas. Press Add a tea, and it prints Counted 4 teas.
Asha is waiting for boxes of tea. She could walk out to the porch once, after a minute, and count what's there. If a van is late, she misses its boxes. Or she can fit a doorbell. It rings each time a box arrives, and she counts again.
- In real life: Checking the porch once, after a minute
- In JavaScript: A
setTimeout()started inconnectedCallback() - In real life: The doorbell
- In JavaScript: A
MutationObserveror aslotchangelistener - In real life: Counting again at every ring
- In JavaScript: Running
#count()each time the children change - In real life: A late van
- In JavaScript: Part of the page that arrives late
Why it matters: the count stays right however the teas arrive, from the parser or from a script. It's the answer the standard's editors gave in issue 551.
Listening for slotchange
A component with a shadow root can use a slot instead. A shadow root is a private tree inside the element. A <slot> in it shows the element's children in that spot. Stage 3, Shadow DOM, templates, and slots, teaches both. When the children that fill a slot change, the slot fires a slotchange event:
<script src="tea-menu.js"></script> <tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p></tea-menu><button>Add a tea</button> <script> const menu = document.querySelector("tea-menu"); document.querySelector("button").onclick = () => { menu.insertAdjacentHTML("beforeend", "<p>Chai</p>"); };</script>- Line 4 of
tea-menu.jsattaches a shadow root with one slot. Lesson 3.2 showed this is allowed in the constructor. - Line 5 listens for
slotchangeon the slot. - Line 6 counts the elements in the slot with
assignedElements().
It prints Counted 3 teas once the teas arrive, and Counted 4 teas when you press the button. Chrome's guide to custom elements suggests slotchange for watching direct children, because connectedCallback() may run before they're parsed.
Waiting until the page is parsed
Sometimes you only care about the HTML the page came with. Then you can wait until the parser has read all of it. document.readyState is "loading" while it reads. When it finishes, the HTML Standard's steps for the end of parsing set it to "interactive" and fire DOMContentLoaded. The Page & resource loading lesson covers that event.
<script src="tea-menu.js"></script> <tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p></tea-menu><button>Add a tea</button> <script> const menu = document.querySelector("tea-menu"); document.querySelector("button").onclick = () => { menu.insertAdjacentHTML("beforeend", "<p>Chai</p>"); };</script>- Line 3 of
tea-menu.jschecks whether the parser is still reading. - If it is, line 4 counts once, at
DOMContentLoaded.{ once: true }removes the listener after it runs. - If not, line 6 counts at once. A menu made later, by a script, takes this path.
It prints Counted 3 teas. But press Add a tea, and nothing prints. It waits for one moment, not for changes.
Some shops don't open until the morning delivery is on the shelves. The staff wait for the van to finish, then open the doors and count the stock once. A box that arrives in the afternoon isn't in that count.
- In real life: The van unloading
- In JavaScript: The parser reading the page
- In real life: Opening the doors when it's done
- In JavaScript:
DOMContentLoaded, or a module script running - In real life: Counting the stock once
- In JavaScript: Counting the teas once
- In real life: A box that arrives in the afternoon
- In JavaScript: A tea added later by a script
Loading the class after the HTML
You can also change the page instead of the class. A module script waits until the parser has read the whole page. MDN says module scripts defer by default. Here is Asha's page with one change on line 1: type="module".
<script type="module" src="tea-menu.js"></script> <tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p></tea-menu>It shows 3 teas on the menu. Every menu in the HTML is upgraded with its teas, as on Ravi's page. Lesson 1.4 loads its components this way. But the class itself is still fragile. A page that loads it with a plain script, or adds teas later, still gets the wrong count.
Why setTimeout and requestAnimationFrame aren't enough
Some tutorials wait a moment instead. setTimeout() runs a function once the current work is done. requestAnimationFrame() runs it just before the browser draws the next frame. The Timers and Animation lessons cover them. Here, both seem to work:
<script src="tea-menu.js"></script> <tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p></tea-menu><button>Add a tea</button> <script> const menu = document.querySelector("tea-menu"); document.querySelector("button").onclick = () => { menu.insertAdjacentHTML("beforeend", "<p>Chai</p>"); };</script>- Lines 3 to 5 of
tea-menu.jscount in a timer with no delay. - Lines 6 to 8 count before the next frame.
Both print 3 teas. In this result frame, the whole page arrives at once. The parser reads every tea before either one runs.
Real pages often arrive in parts. A slow network, or a server still building the page, sends the first part and the rest later. The parser reads what it has, then waits. While it waits, the browser runs timers and draws frames. The course sent a five-tea page in two parts, with a pause between them, and watched Chrome:
DOMContentLoaded waits for the end.Both printed 2 teas. They ran in the pause, after Oolong and Green but before the last three. The MutationObserver version counted 2, then 5. The DOMContentLoaded version counted 5. So timers and frames don't wait for children. They only rely on timing: right on a fast page, wrong on a slow one.
Now sort them all. Which ones end up counting all five teas on the slow page?
- Counting in
connectedCallback() - Counting in a
setTimeout()callback - Counting in a
requestAnimationFrame()callback - A
MutationObserveron the menu's children - A
slotchangelistener on a slot - Waiting for
DOMContentLoadedwhile the page is loading - Loading the class with
<script type="module">
Sort each way of reading the teas by what Chrome printed on the slow page.
Building a tea menu that counts its teas
Ravi puts it together. His menu shows its count, keeps it right as teas arrive, and stops watching while it's off the page:
<style> tea-menu::before { content: attr(data-count) " teas on the menu"; font-weight: bold; }</style><script src="tea-menu.js"></script> <tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p></tea-menu><button id="add">Add a tea</button><button id="away">Take the menu away</button><button id="back">Put it back</button> <script> const menu = document.querySelector("tea-menu"); document.querySelector("#add").onclick = () => menu.insertAdjacentHTML("beforeend", "<p>Chai</p>"); document.querySelector("#away").onclick = () => menu.remove(); document.querySelector("#back").onclick = () => document.body.prepend(menu);</script>- Line 2 of
tea-menu.jsmakes one observer for each menu, as a private field. Making it during construction is fine. It doesn't touch attributes or children. - Lines 4 to 7 count at connect, then start watching.
- Lines 9 to 11 stop watching when the menu leaves. Lesson 3.3 showed why cleanup matters.
- Line 14 stores the count in a
data-countattribute. Line 2 of the page shows it above the teas with CSS. - On the page, lines 17 to 19 add a tea, take the menu away, and put it back.
It shows 3 teas on the menu as soon as the page loads. Add a tea, and it shows 4. Now take the menu away, add a tea, and put it back: 5. While the menu was away, nothing counted. Putting it back ran connectedCallback(), which counted again.
The course made this menu in all six ways from the table, and on the slow page, in Chrome. Each time, it ended with the right count.
The tea kit doesn't change in this lesson. Its components read only attributes, and every row of the table has the attributes by the time connectedCallback() runs. The kit's card, which shows its children, comes back in stage 3 with a slot.
Common mix-ups
- "
connectedCallback()runs after the element's children are parsed." No. With the class loaded first, the parser runs it at the opening tag, before any child. - "The order of the callbacks depends on how the element is made." No. It's always the constructor, then the attribute callbacks, then
connectedCallback(). Only what they see changes. - "A zero-delay
setTimeout()runs after the page is parsed." No. It runs when the browser is free, and that can be while the parser waits for more of the page. - "A
MutationObservertells you when the last child has arrived." No. It tells you each time the children change. Count again every time. - "
cloneNode(true)runs all of the copy's callbacks when you add it." No. The constructor andattributeChangedCallback()run insidecloneNode(), off the page. - "A template's copy holds ready components." No.
template.content.cloneNode(true)makes plain elements. They upgrade when they join the page. Usedocument.importNode()to upgrade them straight away. - "If a child is in
this.children, its class has run." No. WithinnerHTMLor an upgrade, the parent connects first, and the child upgrades after.
Practice exercises
Answer first, then use the hints. The solutions run live, so you can check yourself.
This page uses the overview's tea-menu.js. The menu has four teas. How many does connectedCallback() count?
<script src="tea-menu.js"></script>
<tea-menu>
<p>Oolong</p>
<p>Green</p>
<p>Black</p>
<p>Jasmine</p>
</tea-menu><script src="tea-menu.js"></script> <tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p> <p>Jasmine</p></tea-menu>0. The class loads first, so connectedCallback() runs at the opening tag, before the parser reads any of the four teas. It prints Counted 0 teas.
This page uses the timing table's tea-menu.js, loaded last. How many teas does the constructor see?
<tea-menu name="Spring">
<p>Oolong</p>
<p>Green</p>
<p>Black</p>
<p>Jasmine</p>
</tea-menu>
<script src="tea-menu.js"></script><tea-menu name="Spring"> <p>Oolong</p> <p>Green</p> <p>Black</p> <p>Jasmine</p></tea-menu> <script src="tea-menu.js"></script>4. The menu waited with its name and all four teas. define() upgrades it, so the constructor prints constructor: name Spring, teas 4, connected true, parent BODY.
What does the starter print? Then change the class, so it also prints the right count once the teas arrive.
<script> class TeaMenu extends HTMLElement { connectedCallback() { console.log(`Counted ${this.children.length} teas`); } } customElements.define("tea-menu", TeaMenu);</script> <tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p></tea-menu><script> class TeaMenu extends HTMLElement { connectedCallback() { this.#count(); new MutationObserver(() => this.#count()).observe(this, { childList: true }); } #count() { console.log(`Counted ${this.children.length} teas`); } } customElements.define("tea-menu", TeaMenu);</script> <tea-menu> <p>Oolong</p> <p>Green</p> <p>Black</p></tea-menu>The starter prints Counted 0 teas. The fix counts at connect, then again when the observer sees the teas arrive: Counted 0 teas, then Counted 3 teas.
What kind of error does the starter throw? Then fix it with one change on line 18.
<div id="board"></div><template id="menu-template"> <tea-menu> <p>Oolong</p> <p>Green</p> </tea-menu></template> <script> class TeaMenu extends HTMLElement { count() { return this.children.length; } } customElements.define("tea-menu", TeaMenu); const template = document.querySelector("#menu-template"); const copy = template.content.cloneNode(true); console.log(`Teas: ${copy.querySelector("tea-menu").count()}`); document.querySelector("#board").append(copy);</script><div id="board"></div><template id="menu-template"> <tea-menu> <p>Oolong</p> <p>Green</p> </tea-menu></template> <script> class TeaMenu extends HTMLElement { count() { return this.children.length; } } customElements.define("tea-menu", TeaMenu); const template = document.querySelector("#menu-template"); const copy = document.importNode(template.content, true); console.log(`Teas: ${copy.querySelector("tea-menu").count()}`); document.querySelector("#board").append(copy);</script>A TypeError: count is not a function. cloneNode() on a template's content makes a plain tea-menu, without the class. importNode() copies into the page's document, which upgrades it, so the page prints Teas: 2.
What does the starter print? Then fix it without changing either class.
<tea-menu> <tea-item price="4">Oolong</tea-item> <tea-item price="3">Green</tea-item> <tea-item price="5">Black</tea-item></tea-menu> <script> class TeaMenu extends HTMLElement { connectedCallback() { let total = 0; for (const item of this.children) total += item.price; console.log(`Total: ${total}`); } } class TeaItem extends HTMLElement { get price() { return Number(this.getAttribute("price")); } } customElements.define("tea-menu", TeaMenu); customElements.define("tea-item", TeaItem);</script><tea-menu> <tea-item price="4">Oolong</tea-item> <tea-item price="3">Green</tea-item> <tea-item price="5">Black</tea-item></tea-menu> <script> class TeaMenu extends HTMLElement { connectedCallback() { let total = 0; for (const item of this.children) total += item.price; console.log(`Total: ${total}`); } } class TeaItem extends HTMLElement { get price() { return Number(this.getAttribute("price")); } } customElements.define("tea-item", TeaItem); customElements.define("tea-menu", TeaMenu);</script>Total: NaN. Line 20 upgrades the menu first. Its connectedCallback() runs while the items are still plain, so item.price is undefined. Swap lines 20 and 21: the items upgrade first, and it prints Total: 12.
This page uses the timing table's tea-menu.js. How many callback lines print before Adding the box?
<p>Today's menus:</p>
<script src="tea-menu.js"></script>
<script>
const box = document.createElement("div");
box.innerHTML = `<tea-menu name="Winter"><p>Oolong</p><p>Green</p></tea-menu>`;
console.log("Adding the box");
document.body.append(box);
</script><p>Today's menus:</p> <script src="tea-menu.js"></script> <script> const box = document.createElement("div"); box.innerHTML = `<tea-menu name="Winter"><p>Oolong</p><p>Green</p></tea-menu>`; console.log("Adding the box"); document.body.append(box);</script>Two. innerHTML upgrades the menu before line 7 ends, so the constructor and attributeChangedCallback() print with connected false, parent DIV. connectedCallback() runs inside line 9, when the box joins the page.
Check your understanding
For each question, ask two things: how was the element made, and what was already there?
Question 1 of 8The class is already defined when the parser reads
<tea-menu name="Winter">. In what order do its callbacks run?Choose an answer to see the explanation.
Question 2 of 8In that same case, what does
this.children.lengthgive insideconnectedCallback()?Choose an answer to see the explanation.
Question 3 of 8Which of these runs the copy's constructor before the copy is on the page?
Choose an answer to see the explanation.
Question 4 of 8This page uses the timing table's tea-menu.js. What does it print between
CopyingandAdding?Read the code, then predict<div id="board"></div> <template id="menu-template"> <tea-menu name="Winter"><p>Oolong</p></tea-menu> </template> <script src="tea-menu.js"></script> <script> const template = document.querySelector("#menu-template"); console.log("Copying"); const copy = template.content.cloneNode(true); console.log("Adding"); document.querySelector("#board").append(copy); </script>Choose an answer to see the explanation.
Question 5 of 8Why can a
setTimeout()started inconnectedCallback()miss some children?Choose an answer to see the explanation.
Question 6 of 8What does a
MutationObserveron the menu add thatconnectedCallback()alone can't?Choose an answer to see the explanation.
Question 7 of 8A menu moves into another document with
append(). Which callback runs betweendisconnectedCallback()andconnectedCallback()?Choose an answer to see the explanation.
Question 8 of 8The menu's class has
connectedMoveCallback(). What runs whenmoveBefore()moves it to another shelf?Choose an answer to see the explanation.
Key takeaways
- The callbacks run in one order: the constructor,
attributeChangedCallback()for each watched attribute, thenconnectedCallback(). Moves, adoptions, anddisconnectedCallback()come later. - A move with
append()runsdisconnectedCallback(), thenconnectedCallback().moveBefore()runs onlyconnectedMoveCallback(). A new document addsadoptedCallback()in between. - What a callback sees depends on how the element was made. An upgrade,
innerHTML, and copies already have their attributes and children. - With the class loaded first, the parser runs
connectedCallback()at the opening tag, before any children. cloneNode()upgrades a copy before it returns. A template's copy upgrades only when it joins the page.- To read children, watch them with a
MutationObserverorslotchange.DOMContentLoadedand module scripts cover only the HTML the page came with. Timers only rely on timing.
Remember the one-liner.
The order never changes, but what the element already has does: watch its children instead of counting them once.
Sources
The facts on this page come from these standards, docs, and source files:
- Using custom elements: Custom element lifecycle callbacks, MDN.
- HTML Standard: Custom element reactions, WHATWG.
- HTML Standard: Upgrade an element, WHATWG.
- DOM Standard: Create an element, WHATWG.
- DOM Standard: Insert, WHATWG.
- DOM Standard: Clone a node, WHATWG.
- Node: cloneNode() method, Using cloneNode() with templates, MDN.
- CustomElementDefinition::CreateElement() in custom_element_definition.cc, at Chromium 158.0.8127.18, Chromium.
- HTML Standard: Create an element for a token, WHATWG.
- HTML Standard: Insert an element at the adjusted insertion location, WHATWG.
- connectedCallback timing when the document parser creates custom elements (issue 551), WICG webcomponents.
- Need a callback for when children changed or parser finished parsing children (issue 809), WICG webcomponents.
- Modern Web Guidance: Custom Elements, Upgrade timing and :defined, Chrome for Developers.
- MutationObserver, MDN.
- HTMLSlotElement: slotchange event, MDN.
- HTML Standard: The end, WHATWG.
- <script>: the defer attribute and module scripts, MDN.
Coming next: How elements upgrade when their definition loads. Undefined elements, the upgrade, and how to wait for it.