completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

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.

By the end, you can
  • 01
    Name every callback in orderThe constructor, attributeChangedCallback(), connectedCallback(), and then moves, adoptions, and disconnectedCallback().
  • 02
    Predict what each callback can seeAttributes, children, isConnected, and the parent, for the parser, createElement(), innerHTML, an upgrade, and copies.
  • 03
    Read children safelyWatch them with a MutationObserver or slotchange, 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:

Asha's page loads the class firstPop out in the code editor (opens in a new tab)HTML
<script src="tea-menu.js"></script> <tea-menu>  <p>Oolong</p>  <p>Green</p>  <p>Black</p></tea-menu>
ResultLoading…
Ravi's page loads the class lastPop out in the code editor (opens in a new tab)HTML
<tea-menu>  <p>Oolong</p>  <p>Green</p>  <p>Black</p></tea-menu> <script src="tea-menu.js"></script>
ResultLoading…
  • In tea-menu.js, line 3 counts the menu's children. children holds 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.

Two pages with the same tea menu. On Asha's page, the class loads first: the parser reads the opening tea-menu tag, runs connectedCallback, which counts 0 teas, and only then reads Oolong, Green, and Black. On Ravi's page, the class loads last: the parser reads the tag and all three teas, then define runs connectedCallback, which counts 3 teas.Asha's page: the class loads first<tea-menu>connectedCallback()OolongGreenBlackcounts 0 teasRavi's page: the class loads last<tea-menu>OolongGreenBlackdefine()connectedCallback()counts 3 teas
With the class loaded first, connectedCallback() runs at the opening tag, before the teas exist. With the class loaded last, define() upgrades a menu that already has them.
Real-life analogyA kitchen ticket printed before the dishes are cooked

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.length in connectedCallback()
In real life: A cook who starts after the dishes are out
In JavaScript: An upgrade: the class loads after the HTML
The main idea

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:

One menu's whole life, callback by callbackPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • In tea-menu.js, the second tab, line 2 asks to hear about the name attribute. 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 its content.
  • 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:

The menu's whole life, line by line. Line 10 creates the menu: constructor. Line 11 names it Winter: attributeChangedCallback. Line 12 adds it to the shelf: connectedCallback. Line 13 renames it Spring: attributeChangedCallback. Line 14 moves it to Featured with moveBefore: connectedMoveCallback. Line 15 puts it into the template's storeroom: disconnectedCallback, then adoptedCallback. Line 16 brings it back to the shelf: adoptedCallback, then connectedCallback. Line 17 removes it: disconnectedCallback.line 10creates the menuconstructorline 11names it WinterattributeChangedCallbackline 12adds it to the shelfconnectedCallbackline 13renames it SpringattributeChangedCallbackline 14moves it to FeaturedconnectedMoveCallbackline 15into the storeroomdisconnectedCallbackadoptedCallbackline 16back to the shelfadoptedCallbackconnectedCallbackline 17removes itdisconnectedCallback
Each line of the script, and the callbacks it runs, in order. Lines 15 and 16 run two callbacks each, because the menu changes documents on the way.

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() runs disconnectedCallback(), then connectedCallback(). A move with moveBefore() runs only connectedMoveCallback(), if the class has one.
  • A trip into another document runs disconnectedCallback(), adoptedCallback(), then connectedCallback(). 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.

Real-life analogyA teapot's day at Leaf and Kettle

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:

Playground: one menu, six ways to make it
A tea menu that reports what it seesPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The parser, with the class loaded first

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.

Pick a way to make the menu. The page changes; tea-menu.js, the second tab, stays the same. Each choice runs in a fresh page, and the console lists the callbacks in the order they ran.
  • In tea-menu.js, line 2 watches the name attribute.
  • Lines 6, 10, and 14 call report() from the constructor and the two callbacks.
  • Line 19 reads the name. It's null when 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's true while 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:

What each lifecycle callback sees
How the menu is madeconstructor()attributeChangedCallback()connectedCallback()
The parser, with the class loaded firstAt the opening tag. name null, teas 0, connected false, parent noneAt the opening tag. name Winter, teas 0, connected false, parent noneAt the opening tag. name Winter, teas 0, connected true, parent DIV
An upgrade, with the class loaded after the HTMLInside define(). name Winter, teas 3, connected true, parent DIVInside define(). name Winter, teas 3, connected true, parent DIVInside define(). name Winter, teas 3, connected true, parent DIV
createElement(), then append()Inside createElement(). name null, teas 0, connected false, parent noneInside setAttribute(). name Winter, teas 0, connected false, parent noneInside append(). name Winter, teas 3, connected true, parent DIV
innerHTMLAs the innerHTML line ends. name Winter, teas 3, connected true, parent DIVAs the innerHTML line ends. name Winter, teas 3, connected true, parent DIVAs 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 noneInside cloneNode(). name Winter, teas 3, connected false, parent noneInside append(). name Winter, teas 3, connected true, parent DIV
A template's content, copied and addedInside append(). name Winter, teas 3, connected true, parent DIVInside append(). name Winter, teas 3, connected true, parent DIVInside 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. With createElement(), it depends on your script. Here, the teas went in before append().
  • 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. isConnected is false in the first two callbacks of the parser, createElement(), and cloneNode() 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.

Real-life analogyThree photos of the same shelf

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(), and connectedCallback()
In real life: The shelf's sign
In JavaScript: The name attribute
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:

  1. 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.
  2. It runs the constructor straight away. The menu has no attributes and no children.
  3. It adds the tag's attributes. That queues attributeChangedCallback() for name, and the parser runs the queue at once. The menu still isn't on the page.
  4. 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.
  5. 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:

A menu connects before its items are upgradedPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.
  • :defined matches 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:

A menu that counts again when its children changePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 3 of tea-menu.js counts once, at connect. That covers an upgrade, where the teas are already there.
  • Line 4 makes an observer and starts it. childList: true means "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.

Real-life analogyA doorbell that rings for every delivery

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 in connectedCallback()
In real life: The doorbell
In JavaScript: A MutationObserver or a slotchange listener
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:

A menu that counts the teas in its slotPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 4 of tea-menu.js attaches a shadow root with one slot. Lesson 3.2 showed this is allowed in the constructor.
  • Line 5 listens for slotchange on 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.

A menu that waits for the page to be parsedPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 3 of tea-menu.js checks 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.

Real-life analogyOpening the doors after the van is unloaded

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".

Asha's page, with the class loaded as a modulePop out in the code editor (opens in a new tab)HTML
<script type="module" src="tea-menu.js"></script> <tea-menu>  <p>Oolong</p>  <p>Green</p>  <p>Black</p></tea-menu>
ResultLoading…

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:

A menu that counts a moment laterPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Lines 3 to 5 of tea-menu.js count 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:

The slow page arrives in two parts with a pause between them. Part 1 holds the menu's opening tag, Oolong, and Green. Part 2 holds Black, Jasmine, and Chai. connectedCallback counts 0 teas at the opening tag. setTimeout and requestAnimationFrame both run in the pause and count 2. The MutationObserver counts 2 after part 1 and 5 after part 2. DOMContentLoaded waits for the end and counts 5.part 1 arrivespausepart 2 arrivesmenu, Oolong, GreenBlack, Jasmine, ChaiconnectedCallback0 teassetTimeout2 teasrequestAnimationFrame2 teasMutationObserver2 teas5 teasDOMContentLoaded5 teas
The timer and the frame callback run in the pause, so they count 2 of the 5 teas. The observer counts again after each part, and 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?

Will it count all five teas on the slow page?
  • Counting in connectedCallback()
  • Counting in a setTimeout() callback
  • Counting in a requestAnimationFrame() callback
  • A MutationObserver on the menu's children
  • A slotchange listener on a slot
  • Waiting for DOMContentLoaded while the page is loading
  • Loading the class with <script type="module">
Try it yourself
0 of 7 correct

Sort each way of reading the teas by what Chrome printed on the slow page.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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:

The finished tea menuPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 2 of tea-menu.js makes 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-count attribute. 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 MutationObserver tells 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 and attributeChangedCallback() run inside cloneNode(), 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. Use document.importNode() to upgrade them straight away.
  • "If a child is in this.children, its class has run." No. With innerHTML or 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.

Exercise 1 · Warm-upCount at the opening tag

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>

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upWhat an upgrade sees

    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>

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeCount the teas with a MutationObserver

      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>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFind the bug in the template copy

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeFind the bug in the menu's total

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeA menu built in a box off the page

            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>

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask two things: how was the element made, and what was already there?

              The lifecycle order quiz · 8 questionsScore: first tries count
              1. 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.

              2. Question 2 of 8In that same case, what does this.children.length give inside connectedCallback()?

                Choose an answer to see the explanation.

              3. 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.

              4. Question 4 of 8This page uses the timing table's tea-menu.js. What does it print between Copying and Adding?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              5. Question 5 of 8Why can a setTimeout() started in connectedCallback() miss some children?

                Choose an answer to see the explanation.

              6. Question 6 of 8What does a MutationObserver on the menu add that connectedCallback() alone can't?

                Choose an answer to see the explanation.

              7. Question 7 of 8A menu moves into another document with append(). Which callback runs between disconnectedCallback() and connectedCallback()?

                Choose an answer to see the explanation.

              8. Question 8 of 8The menu's class has connectedMoveCallback(). What runs when moveBefore() 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, then connectedCallback(). Moves, adoptions, and disconnectedCallback() come later.
              • A move with append() runs disconnectedCallback(), then connectedCallback(). moveBefore() runs only connectedMoveCallback(). A new document adds adoptedCallback() 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 MutationObserver or slotchange. DOMContentLoaded and 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:

              Coming next: How elements upgrade when their definition loads. Undefined elements, the upgrade, and how to wait for it.

              CompleteFrontend Clear concepts. Working examples.