How elements upgrade when their definition loads
Learn how a custom element upgrade works: which tags define() reaches, what runs, and how to use customElements.upgrade(), whenDefined(), get(), and getName().
- 01Predict which elements upgrade, and whenTell which tags
define()reaches, in what order, and which ones wait until they join the page. - 02Say what runs during an upgradeThe same element gets your class, then its constructor and callbacks run, and a failed upgrade is never tried again.
- 03Use the registry's other methodsUpgrade elements off the page with
customElements.upgrade(), wait withwhenDefined(), and look things up withget()andgetName().
What is a custom element upgrade?
Ravi's menu page for Leaf and Kettle loads the tea kit last. On a slow phone, the kit can arrive two seconds after the page. Until then, each <tea-label> just shows the words inside it.
Ravi's own script runs first. It grabs a label and adds a click handler to it. Then the kit arrives, and the label changes. Is it still the label his script grabbed? Will his click handler still run?
A custom element upgrade is the moment an element that is already on the page gets its class. The browser keeps the same element, gives it your class, and runs your constructor on it. Then it runs attributeChangedCallback() and connectedCallback(). So the answer to both questions is yes. Here is Ravi's page, with the kit's label loaded two seconds late:
<tea-label name="Green tea" minutes="3">Green tea</tea-label> <script type="module"> const waiting = document.querySelector("tea-label"); waiting.addEventListener("click", () => console.log("Clicked")); console.log("Before:", waiting.constructor.name); await new Promise((resolve) => setTimeout(resolve, 2000)); await import("./tea-kit/tea-label.js"); console.log("After:", waiting.constructor.name); console.log("Same element:", waiting === document.querySelector("tea-label"));</script>- Line 1 is the label, with the words
Green teainside. Nothing has definedtea-labelyet. - Line 4 keeps the label in a variable called
waiting. Line 5 adds a click handler to it. - Line 6 prints the name of the label's class:
Before: HTMLElement. Every waiting tag is a plainHTMLElement. - Line 8 waits two seconds, like a slow network. Line 9 loads the kit's
tea-label.js, the second tab, withimport(). It loads a file while the page runs, as the Dynamic import lesson shows. The file's last line callscustomElements.define(). - Line 11 prints
After: TeaLabel. Line 12 printsSame element: true.
Watch the result. It shows Green tea for two seconds, then Green tea: brew for 3 minutes. Now click the label. The console prints Clicked. The handler from line 5 still works, because nothing was swapped. The browser changed the element in place.
Leaf and Kettle opens a new shop. On the first morning, the staff work in their own clothes. Customers already know them by name. At noon, the box of uniforms arrives. The manager doesn't hire new people. She hands each person a uniform, and they carry on.
- In real life: Staff working in their own clothes
- In JavaScript: Tags waiting as plain
HTMLElements - In real life: The box of uniforms arriving
- In JavaScript:
customElements.define()with your class - In real life: Handing each person a uniform
- In JavaScript: Upgrading each element, in place
- In real life: Customers who already know them by name
- In JavaScript: Your references and click handlers
An upgrade doesn't make a new element. The browser gives the element that is already there your class, then runs your constructor and callbacks on it. Its place on the page stays. So do its attributes, its children, and every reference to it.
You've seen upgrades from the page's side. Lesson 1.1 showed a tag that waits for its class. Lesson 2.4 showed what a waiting tag looks like. Lesson 3.6 showed that an upgrade runs its callbacks inside define(). This lesson looks from your side, as the author of the class. Which elements will it meet, and what runs on them?
Which elements does customElements.define() upgrade?
When you call define(), the browser looks for elements to upgrade. The HTML Standard calls them upgrade candidates. Its steps for define() pick every element with the new name that is in the document. They look inside shadow roots too. Then they queue an upgrade for each one, in page order.
<tea-label>Oolong</tea-label><div id="box"></div><tea-label>Black</tea-label> <script> const box = document.querySelector("#box"); box.attachShadow({ mode: "open" }).innerHTML = "<tea-label>Green</tea-label>"; const loose = document.createElement("tea-label"); class TeaLabel extends HTMLElement { connectedCallback() { console.log("Upgraded", this.textContent); } } customElements.define("tea-label", TeaLabel); console.log("Loose label upgraded:", loose instanceof TeaLabel);</script>- Lines 1 to 3 are the page: a label, an empty box, and another label.
- Line 7 gives the box a shadow root: a private tree of its own, as in lesson 1.1. It puts a third label, Green, inside it.
- Line 8 makes a fourth label with
createElement(). It's never added to the page. Call it the loose label. - Lines 10 to 14 are the class. Each label prints its text when its
connectedCallback()runs. - Line 15 registers the class. Line 16 checks the loose label.
The console prints Upgraded Oolong, Upgraded Green, Upgraded Black, and then Loose label upgraded: false. That shows three rules:
- Page order. The browser walks the page from top to bottom. The spec calls it shadow-including tree order.
- Shadow roots count. When the walk reaches the box, it goes into the box's shadow root before it moves on. So Green comes second. A closed shadow root is no different.
- Only the document. The loose label isn't in the document, so
define()never sees it. It keeps waiting.
define() walks the page from top to bottom, and goes into a shadow root when it reaches its host. The loose label isn't in the page, so it waits.Think of the manager with the uniforms. She walks the shop from the door to the back, and steps into each side room as she passes it. Someone on a day off doesn't get a uniform today.
Chrome doesn't search the whole page when you call define(). It keeps a list of waiting elements for each name. CollectCandidates() takes the list for the new name and sorts it into page order.
One element at a time
Each upgrade finishes before the next one starts. The first element's constructor and callbacks all run first. So while one element upgrades, the ones after it are still waiting:
<tea-label>Oolong</tea-label><tea-label>Green</tea-label><tea-label>Black</tea-label> <script> class TeaLabel extends HTMLElement { connectedCallback() { const ready = document.querySelectorAll("tea-label:defined").length; console.log(`${this.textContent}: ${ready} of 3 ready`); } } customElements.define("tea-label", TeaLabel);</script>- Lines 1 to 3 are three labels.
- Line 8 counts the labels that match
:definedright now.:definedmatches a custom element once its upgrade has finished. - Line 9 prints the label's text and the count.
It prints Oolong: 1 of 3 ready, then Green: 2 of 3 ready, then Black: 3 of 3 ready. When Oolong's callback runs, Green and Black are still plain elements. Domenic Denicola's note on why upgrades exist points out this moment. An element that looks at its neighbor during an upgrade can find it not upgraded yet.
Why it matters: during its own upgrade, a component can't rely on the components after it. Lesson 3.6 met the same problem with a menu and its items.
What happens during a custom element upgrade?
An upgrade is a short list of steps in the HTML Standard, called upgrade an element. Here they are in plain words, for one waiting element:
- If the element isn't waiting anymore, stop. No element is upgraded twice.
- Mark the element as failed, for now. If a second upgrade of it starts in the middle of this one, step 1 stops it.
- Queue a call to
attributeChangedCallback()for each attribute the element has. Only the ones inobservedAttributeswill run. - If the element is in a document, queue a call to
connectedCallback(). - Mark the element as precustomized, and run your constructor on it.
- If the constructor throws, drop the queued calls and stop. The element isn't waiting now, so step 1 stops any later try.
- Otherwise, mark the element as custom. Then the queued calls run.
Failed, precustomized, and custom are states from the list in lesson 2.4. A waiting element's state is undefined. While the constructor runs, it's precustomized, so :defined doesn't match yet. Lesson 3.4 showed the order of the attribute calls: the tag's order, each one from null.
How the constructor runs on an element that exists
Step 5 sounds odd. A constructor normally makes a new object. How can it run on one that already exists? The answer is in super().
Before step 5, the browser puts the waiting element on a short list that belongs to your class. The standard calls it the construction stack. Your constructor calls super(), which runs HTMLElement's constructor. That constructor checks the list and finds the waiting element. It gives the element your class's prototype, the object that holds your methods. Then it returns the element, and that becomes this. The standard spells this out in its steps for HTML element constructors. The prototype chain lesson explains prototypes.
Try both choices. The same page upgrades one label, with a constructor that works or one that throws:
<tea-label name="Green">Green tea</tea-label> <script> const waiting = document.querySelector("tea-label"); class TeaLabel extends HTMLElement { static observedAttributes = ["name"]; constructor() { super(); console.log("constructor, same element:", this === waiting); // Nothing goes wrong here. } attributeChangedCallback(name, oldValue, newValue) { console.log("attributeChangedCallback:", oldValue, "to", newValue); } connectedCallback() { console.log("connectedCallback"); } } customElements.define("tea-label", TeaLabel); console.log("define() returned. :defined is", waiting.matches(":defined")); console.log("instanceof TeaLabel is", waiting instanceof TeaLabel); customElements.upgrade(waiting);</script>The constructor runs on the element that was already on the page. Then attributeChangedCallback() runs for name, then connectedCallback(). All of it happens inside define(). Line 23 asks for a second upgrade, and nothing happens: the element is already custom.
- Line 4 keeps the waiting label in
waiting. - Line 7 watches the
nameattribute. - Line 10 checks that
thisis the waiting label. - Line 11 is the only line that changes. It either does nothing or throws.
- Lines 20 to 22 register the class, then check the label with
:definedandinstanceof. - Line 23 asks for a second upgrade of the same label.
With a working constructor, five lines print. The constructor says same element: true. Then come attributeChangedCallback: null to Green and connectedCallback, all before define() returns. Line 23 prints nothing, because the label is already custom.
Now pick The constructor throws. The console shows Error: The label broke, but define() doesn't throw. Line 21 still runs and prints :defined is false. The two callbacks never run. And line 23 doesn't try again. Once an upgrade fails, it fails for good.
Look at line 22 in that run. It prints instanceof TeaLabel is true, even though the upgrade failed. The super() call had already given the label its prototype before line 11 threw. So instanceof can't tell you an upgrade worked. :defined can.
custom as soon as the constructor finishes, and then the queued callbacks run. If the constructor throws, the upgrade fails for good.The café's armchairs are getting new covers. The upholsterer works on each chair where it stands. She doesn't swap it for another chair, and the coats on it stay put. If the fabric tears halfway, she leaves that chair and never comes back to it.
- In real life: The armchair
- In JavaScript: The waiting element
- In real life: Working on it where it stands
- In JavaScript: The constructor running on that element, as
this - In real life: The coats left on it
- In JavaScript: Its attributes, children, and listeners
- In real life: The new cover
- In JavaScript: Your class's prototype and methods
- In real life: A torn cover, never redone
- In JavaScript: A constructor that throws: the upgrade fails for good
Why it matters: your constructor may meet an element that already has attributes, children, and listeners. That's why lesson 3.2 says not to read them there. And keep the constructor simple. If it throws, that element never gets a second chance.
What does customElements.upgrade() do?
define() only looks in the document. But scripts often build elements off the page first, then add them. Those elements can upgrade in two ways:
- When they join the page. The DOM Standard's insert steps check every element that joins a document. For each one that is still waiting, they try to upgrade it: look up its name, and upgrade it if a class is defined.
- When you call
customElements.upgrade(root). It tries to upgraderootand every element inside it, shadow roots too. It works off the page.
Here a script makes a price before the kit loads, and upgrades it before it joins the page:
<p id="shelf">Green tea.</p> <script type="module"> const price = document.createElement("tea-price"); price.setAttribute("amount", "4"); const { TeaPrice } = await import("./tea-kit/tea-price.js"); console.log("After define():", price instanceof TeaPrice); customElements.upgrade(price); console.log("After upgrade():", price.textContent); document.querySelector("#shelf").append(" ", price);</script>- Line 4 makes a
tea-pricebefore the kit has loaded. Line 5 sets its amount. - Line 7 loads the kit's
tea-price.js, the second tab. It definestea-priceand gives back its class. - Line 8 prints
After define(): false. The price is off the page, sodefine()skipped it. - Line 10 upgrades it. Line 11 prints
After upgrade(): Price: 4. - Line 13 adds it to the shelf.
Where did Price: 4 come from? In tea-price.js, attributeChangedCallback() draws the text. During the upgrade, it ran for amount, as step 3 says. connectedCallback() didn't run, because the price wasn't in a document yet. It runs on line 13.
New tables arrive flat-packed. The staff could build each one in the café, in front of customers. Or they can build it in the back room, check that it stands, and carry it out ready.
- In real life: The flat-pack box
- In JavaScript: An element off the page, still waiting
- In real life: Building it in the back room
- In JavaScript:
customElements.upgrade(element) - In real life: Carrying it into the café
- In JavaScript: Adding it to the page, which runs
connectedCallback() - In real life: Building it in front of customers
- In JavaScript: Letting it upgrade as it joins the page
Why it matters: after upgrade(), the element has your class's methods, even off the page. You can call them before you add it. It never throws, either. It simply skips elements it can't upgrade:
- Elements that aren't waiting. An element that has upgraded, or whose upgrade failed, is left alone. Line 23 of the steps playground showed it.
- Names with no class yet. Nothing happens, and nothing is remembered. Call it again after
define(). - Elements from another registry. Browsers now let a shadow root have its own registry, a scoped registry. Stage 3 covers them.
customElements.upgrade()skips elements that belong to another one. - Elements whose document has no registry. That's the surprise in the next section.
Why doesn't customElements.upgrade() upgrade a template copy?
People ask this on Stack Overflow. They copy a <template>'s content, call upgrade() on the copy, and its elements stay plain. Here is the same thing:
<p id="shelf"></p><template id="row"><tea-label name="Green tea" minutes="3"></tea-label></template> <script type="module"> await import("./tea-kit/tea-label.js"); const template = document.querySelector("#row"); const copy = template.content.cloneNode(true); customElements.upgrade(copy); console.log("Copy made with cloneNode():", copy.firstElementChild.matches(":defined")); const imported = document.importNode(template.content, true); console.log("Copy made with importNode():", imported.firstElementChild.matches(":defined")); document.querySelector("#shelf").append(imported);</script>- Line 2 is a template that holds one label.
- Line 5 loads the kit's label, which defines
tea-label. - Line 8 copies the template's content with
cloneNode(true). Line 9 tries to upgrade the copy. - Line 10 prints
Copy made with cloneNode(): false. - Line 12 copies it with
document.importNode()instead. Line 13 printsCopy made with importNode(): true. - Line 14 adds that copy to the shelf. It shows
Green tea: brew for 3 minutes.
A template's content doesn't belong to the page's document. The browser keeps it in a separate document, made for templates. That document has no window, so it has no registry. A cloneNode() copy stays in that document, as lesson 3.6 showed. And upgrade() skips every element whose registry isn't the one you called it on. These elements have none at all.
importNode() copies the content into the page's document, where the registry is. So its copy is upgraded as it's made. append() works too: it moves the copy into the page, and it upgrades there.
importNode() copies it into the page's document, and append() moves it there. Either way, the copy upgrades in the page.Documents with no window
The same goes for any document without a window. document.implementation.createHTMLDocument() makes one, and so does DOMParser. Elements made in them stay plain, even when the page has defined their names:
<p id="shelf"></p> <script type="module"> await import("./tea-kit/tea-label.js"); const draft = document.implementation.createHTMLDocument("Draft"); const label = draft.createElement("tea-label"); label.setAttribute("name", "Mint tea"); label.setAttribute("minutes", "5"); customElements.upgrade(label); console.log("In the draft:", label.matches(":defined")); document.querySelector("#shelf").append(label); console.log("On the page:", label.matches(":defined"));</script>- Line 5 makes an empty document called
Draft. It has no window. - Line 6 makes a label in it. Lines 7 and 8 give it a name and a time.
- Line 10 tries to upgrade it. Line 11 prints
In the draft: false. - Line 12 moves it into the page. Line 13 prints
On the page: true.
It's like a chair in an architect's model of the shop. Nobody sits on it until it's in the real shop. Why it matters: custom elements you build in another document stay plain until they join the page. Don't call their methods before then.
Try every place
Now compare all five places at once. The playground makes one label, then calls each step and prints its name:
<template><tea-label></tea-label></template><div id="box"></div><script src="tea-label.js"></script> <script> // A label in the page const label = document.createElement("tea-label"); document.body.append(label); console.log("1. define()"); customElements.define("tea-label", TeaLabel); console.log("2. upgrade()"); customElements.upgrade(label); console.log("3. append()"); if (!label.isConnected) document.querySelector("#box").append(label);</script>The label is in the document, so define() finds it. It runs the constructor and connectedCallback() before it returns. Then upgrade() has nothing left to do.
- Line 1 is a template. Only the template choice uses it. Line 2 is an empty box.
- Line 3 loads
tea-label.js, the second tab. It makes the class but doesn't calldefine(). Its constructor andconnectedCallback()each print their name. - Lines 6 to 8 make the label. They change with your choice.
- Lines 10 to 15 print each step, then run it:
define(),upgrade(), and adding the label to the box if it isn't on the page yet.
Read each row across: where the label is, then what each step does to it.
| Where the label is | Does define() upgrade it? | Does upgrade() upgrade it? | When does it upgrade? |
|---|---|---|---|
| In the page | Yes. | It's already upgraded, so nothing happens. | Inside define(). |
| In a shadow root | Yes. | It's already upgraded, so nothing happens. | Inside define(), in page order. |
| Made by a script | No. | Yes. The constructor runs, but connectedCallback() waits. | Inside upgrade(), or when it joins the page. |
| A template copy | No. | No. The copy belongs to the template's document, which has no registry. | When it joins the page. |
| Another document | No. | No. Its document has no window, so it has no registry. | When it joins the page. |
When does customElements.whenDefined() fulfill?
Lesson 2.2 used whenDefined() from the page's side. It waits for a name, and its promise fulfills with the class. A name that is never defined waits forever. That's why lesson 2.4 raced it against a timer with Promise.race(). As an author, you need one more detail. What is ready when the promise fulfills?
<tea-label name="Green tea" minutes="3">Green tea</tea-label><tea-label name="Black tea" minutes="4">Black tea</tea-label> <script type="module"> const loose = document.createElement("tea-label"); customElements.whenDefined("tea-label").then((TeaLabel) => { const labels = [...document.querySelectorAll("tea-label")]; console.log("On the page:", labels.every((label) => label instanceof TeaLabel)); console.log("Off the page:", loose instanceof TeaLabel); }); setTimeout(() => import("./tea-kit/tea-label.js"), 1000);</script>- Lines 1 and 2 are two labels on the page.
- Line 5 makes a third label, off the page.
- Line 7 waits for
tea-label. The promise gives the class, which this code callsTeaLabel. - Line 9 checks that every label on the page is a
TeaLabel. Line 10 checks the loose one. - Line 13 loads the kit's label after one second.
After one second, it prints On the page: true, then Off the page: false.
Here is why. define() queues an upgrade for every candidate, then fulfills the promise. The queued upgrades all run before define() returns. Your then() code runs later still. So by then, every element with that name in the page is upgraded. But the promise is about the name, not about each element. The loose label still waits. If you need it upgraded, call customElements.upgrade() on it.
One promise per name
While a name waits, the registry keeps one promise for it. Every whenDefined() call for that name gets that same promise:
const first = customElements.whenDefined("tea-cup");
const second = customElements.whenDefined("tea-cup");
console.log(first === second);
customElements.define("tea-cup", class extends HTMLElement {});
console.log(customElements.whenDefined("tea-cup") === customElements.whenDefined("tea-cup"));- Lines 1 and 2 ask twice, before
tea-cupis defined. Line 3 printstrue: it's one promise. - Line 5 defines
tea-cup. Line 6 asks twice more and printsfalse. Now each call gets a new promise that has already fulfilled.
Chrome keeps the waiting promises in a map from names to promises. You can see it in its whenDefined(). It's like a crowd at a station watching one departure board. Many components can wait for the same name, and they all wait on that one promise.
How do you check if a custom element is defined?
The registry answers two questions. customElements.get(name) gives the class for a name, or undefined. customElements.getName(class) goes the other way. It gives the name for a class, or null.
class TeaLabel extends HTMLElement {}
customElements.define("shop-label", TeaLabel);
console.log(customElements.get("shop-label") === TeaLabel);
console.log(customElements.get("tea-label"));
console.log(customElements.getName(TeaLabel));
console.log(customElements.getName(HTMLElement));- Line 2 registers
TeaLabelunder another name,shop-label. Say a page renamed the kit's tag to avoid a clash. - Line 4 prints
true.get()gives back the class itself. - Line 5 prints
undefined. Nothing is calledtea-labelhere. - Line 6 prints
shop-label. When you only have the class, this is how you learn its tag name. - Line 7 prints
null.HTMLElementwas never defined as a custom element.
get() turns a name into its class, or undefined. getName() turns a class into its name, or null.The shop keeps a book of its suppliers. Look up a name, and you find their phone number. This book also works the other way. Look up a number, and you find whose it is. If nobody is listed, the book has nothing to show.
- In real life: A supplier's name
- In JavaScript: A tag name, like
shop-label - In real life: Their phone number
- In JavaScript: The class,
TeaLabel - In real life: Looking up a name
- In JavaScript:
customElements.get("shop-label") - In real life: Looking up a number
- In JavaScript:
customElements.getName(TeaLabel) - In real life: Nobody listed
- In JavaScript:
undefinedfromget(),nullfromgetName()
getName() always has one answer, because a registry takes each class only once. A second define() with the same class throws, on purpose:
class TeaLabel extends HTMLElement {}
customElements.define("tea-label", TeaLabel);
customElements.define("shop-label", TeaLabel);Line 3 throws a NotSupportedError. Chrome's message reads this constructor has already been used with this registry. So each class has one name, and getName() can't be unsure.
Checking one element
get() tells you about a name. To ask about one element, use element.matches(":defined"). For a tag with a hyphen, it's true once that element's upgrade has finished. Don't use instanceof for this. The steps playground showed a label whose upgrade failed, where instanceof said true. :defined said false, which was right.
Finding tags that didn't upgrade
Now put it together into a small checking tool. Asha's test page loads the whole kit, but two tags never come to life. One name is spelled wrong. One component's constructor throws. Which is which?
<tea-label name="Green tea" minutes="3">Green tea</tea-label><tea-prcie amount="4">Price: 4</tea-prcie><tea-cup>A cup</tea-cup><button>Check the page</button> <script type="module" src="tea-kit/index.js"></script><script type="module" src="tea-cup.js"></script><script> document.querySelector("button").addEventListener("click", () => { for (const tag of document.querySelectorAll(":not(:defined)")) { const name = tag.localName; const why = customElements.get(name) ? "its constructor threw" : "nothing defines this name"; console.log(`${name} didn't upgrade: ${why}`); } });</script>- Lines 1 to 3 are three tags: a kit label, a misspelled
tea-prcie, and atea-cup. - Line 6 loads the whole kit through
tea-kit/index.js. Line 7 loadstea-cup.js, whose constructor always throws. - Line 10 finds every element that doesn't match
:defined. - Line 12 asks the registry about each name. If there is a class, the name is defined, so the constructor must have thrown. If not, nothing defines the name.
- Line 13 prints the answer.
Click Check the page. The first line it prints is tea-prcie didn't upgrade: nothing defines this name. The second is tea-cup didn't upgrade: its constructor threw. The label upgraded, so it isn't listed.
The loop works on any page. Open DevTools, click the Console tab, and paste it in:
for (const tag of document.querySelectorAll(":not(:defined)")) {
const name = tag.localName;
const why = customElements.get(name) ? "its constructor threw" : "nothing defines this name";
console.log(`${name} didn't upgrade: ${why}`);
}These are lines 10 to 14 from above, without the click. Line 4 prints one line for each tag that didn't upgrade. Mind two limits. Run it after the page has loaded, because a tag whose file is still on its way looks like nothing defines it. And it only sees the page's own tree. Tags inside a component's shadow root don't show up.
Common mix-ups
- "define() upgrades every element with that name." No. It upgrades only the ones in the document, shadow roots included. An element a script made and hasn't added waits until it joins the page, or until you call
customElements.upgrade(). - "An upgrade swaps the element for a new one." No. It's the same object. Your references, listeners, attributes, and children all stay.
- "customElements.upgrade() works on any element." No. It skips a template's
cloneNode()copy, elements from a document with no window, and elements from another registry. UseimportNode(), or add them to the page. - "If instanceof is true, the upgrade worked." No. A constructor that throws after
super()leaves an element that is an instance of your class, but not upgraded. Check:defined. - "A failed upgrade is tried again when you add the element again." No. It fails for good. The browser never runs its constructor again.
- "When whenDefined() fulfills, every element with that name is upgraded." No. Only the ones in the page. An element off the page still waits.
Practice exercises
Answer first, then use the hints. Each result runs live, so you can check yourself.
The page has a label, a box with a label inside it, and a label in the box's shadow root. Which label prints second?
<tea-label>Oolong</tea-label><div id="box"> <tea-label>Black</tea-label></div> <script> const box = document.querySelector("#box"); box.attachShadow({ mode: "open" }).innerHTML = "<tea-label>Green</tea-label> <slot></slot>"; class TeaLabel extends HTMLElement { connectedCallback() { console.log(this.textContent); } } customElements.define("tea-label", TeaLabel);</script>Green. It prints Oolong, Green, Black. Green is in the box's shadow root, which comes before Black, the box's own child.
What does line 5 print?
class TeaLabel extends HTMLElement {}
class SaleLabel extends TeaLabel {}
customElements.define("tea-label", TeaLabel);
console.log(customElements.getName(SaleLabel));null. Only TeaLabel is registered. SaleLabel extends it, but it was never passed to define(), so the registry has no name for it.
Line 8 prints the price's text before it joins the page. Right now it's empty. Add one line at line 7 so the text is there already. What does the console print then?
<p id="shelf">Black tea.</p> <script type="module"> const price = document.createElement("tea-price"); price.setAttribute("amount", "5"); await import("./tea-kit/tea-price.js"); // Add one line here. console.log("Text before it joins the page:", price.textContent); document.querySelector("#shelf").append(" ", price);</script><p id="shelf">Black tea.</p> <script type="module"> const price = document.createElement("tea-price"); price.setAttribute("amount", "5"); await import("./tea-kit/tea-price.js"); customElements.upgrade(price); console.log("Text before it joins the page:", price.textContent); document.querySelector("#shelf").append(" ", price);</script>upgrade() runs the constructor and attributeChangedCallback() off the page. The callback draws Price: 5, so line 8 prints Text before it joins the page: Price: 5.
Line 9 prints Ready before adding: false. Change line 7 so the row is upgraded before it's added. What does the fixed page print?
<p id="shelf"></p><template id="row"><tea-label name="Oolong" minutes="4"></tea-label></template> <script type="module"> await import("./tea-kit/tea-label.js"); const template = document.querySelector("#row"); const row = template.content.cloneNode(true); customElements.upgrade(row); console.log("Ready before adding:", row.firstElementChild.matches(":defined")); document.querySelector("#shelf").append(row);</script><p id="shelf"></p><template id="row"><tea-label name="Oolong" minutes="4"></tea-label></template> <script type="module"> await import("./tea-kit/tea-label.js"); const template = document.querySelector("#row"); const row = document.importNode(template.content, true); customElements.upgrade(row); console.log("Ready before adding:", row.firstElementChild.matches(":defined")); document.querySelector("#shelf").append(row);</script>importNode() copies the content into the page's document, so the label upgrades as it's made. Line 9 prints Ready before adding: true.
How many cups match :defined at the end? What does line 16 print?
<tea-cup>1</tea-cup><tea-cup>2</tea-cup><tea-cup>3</tea-cup> <script> let made = 0; class TeaCup extends HTMLElement { constructor() { super(); made += 1; if (made === 2) throw new Error("Cup 2 cracked"); } } customElements.define("tea-cup", TeaCup); document.body.append(document.querySelectorAll("tea-cup")[1]); console.log(document.querySelectorAll("tea-cup:defined").length);</script>2. Cup 2's constructor throws, so its upgrade fails. Cups 1 and 3 still upgrade. Moving cup 2 on line 15 doesn't try again, because a failed upgrade is never upgraded twice.
Write whenUpgraded(element). It should wait until the element's name is defined, then upgrade the element, even off the page. What does your page print?
<p id="shelf">Mint tea.</p> <script type="module"> async function whenUpgraded(element) { // Wait for the element's name, then upgrade it. } const price = document.createElement("tea-price"); price.setAttribute("amount", "3"); import("./tea-kit/tea-price.js"); await whenUpgraded(price); console.log("Price text:", price.textContent); document.querySelector("#shelf").append(" ", price);</script><p id="shelf">Mint tea.</p> <script type="module"> async function whenUpgraded(element) { await customElements.whenDefined(element.localName); customElements.upgrade(element); } const price = document.createElement("tea-price"); price.setAttribute("amount", "3"); import("./tea-kit/tea-price.js"); await whenUpgraded(price); console.log("Price text:", price.textContent); document.querySelector("#shelf").append(" ", price);</script>Line 5 waits for tea-price to be defined. Line 6 upgrades the price, which is off the page, so define() skipped it. The callback draws the text, and line 13 prints Price text: Price: 3.
Check your understanding
For each question, ask two things: is the element in the page, and is it still waiting?
Question 1 of 7What is a custom element upgrade?
Choose an answer to see the explanation.
Question 2 of 7In the order example, which label's connectedCallback() prints second?
Read the code, then predict<tea-label>Oolong</tea-label> <div id="box"></div> <tea-label>Black</tea-label> <script> const box = document.querySelector("#box"); box.attachShadow({ mode: "open" }).innerHTML = "<tea-label>Green</tea-label>"; const loose = document.createElement("tea-label"); class TeaLabel extends HTMLElement { connectedCallback() { console.log("Upgraded", this.textContent); } } customElements.define("tea-label", TeaLabel); console.log("Loose label upgraded:", loose instanceof TeaLabel); </script>Choose an answer to see the explanation.
Question 3 of 7During one element's upgrade, in what order do these run?
Choose an answer to see the explanation.
Question 4 of 7A script runs
document.createElement("tea-label")beforetea-labelis defined, and doesn't add it to the page. What doesdefine()do to it later?Choose an answer to see the explanation.
Question 5 of 7What does line 10 of the template copy example print?
Read the code, then predict<p id="shelf"></p> <template id="row"><tea-label name="Green tea" minutes="3"></tea-label></template> <script type="module"> await import("./tea-kit/tea-label.js"); const template = document.querySelector("#row"); const copy = template.content.cloneNode(true); customElements.upgrade(copy); console.log("Copy made with cloneNode():", copy.firstElementChild.matches(":defined")); const imported = document.importNode(template.content, true); console.log("Copy made with importNode():", imported.firstElementChild.matches(":defined")); document.querySelector("#shelf").append(imported); </script>Choose an answer to see the explanation.
Question 6 of 7What do
customElements.get()andcustomElements.getName()give back for a name or a class nobody defined?Choose an answer to see the explanation.
Question 7 of 7An element's constructor throws during its upgrade. What happens when you add that element to the page again later?
Choose an answer to see the explanation.
Key takeaways
- An upgrade gives an element that is already there its class. It's the same object, so references, listeners, attributes, and children stay.
define()upgrades the elements with that name in the document, shadow roots included. It goes one at a time, in page order.- Your constructor runs first, on the waiting element. Then
attributeChangedCallback()runs for each watched attribute, thenconnectedCallback()if it's in a document. - If the constructor throws, the upgrade fails for good. Check
:defined, notinstanceof. - Elements off the page upgrade when they join it, or with
customElements.upgrade(). Template copies and elements from documents with no window upgrade only in the page. whenDefined()fulfills with the class after every element in the page is upgraded.get()andgetName()look up names and classes.
Remember the one-liner.
An upgrade gives the element that is already there its class: the same object, the constructor first, then the callbacks.
Sources
The facts on this page come from these standards, docs, and source files:
- HTML Standard: Upgrading elements after their creation, WHATWG.
- HTML Standard: The define() method and upgrade candidates, WHATWG.
- CustomElementRegistry::CollectCandidates() in custom_element_registry.cc, at Chromium 158.0.8127.18, Chromium.
- Why Upgrades, Domenic Denicola, WICG.
- HTML Standard: Upgrade an element, WHATWG.
- HTML Standard: HTML element constructors, WHATWG.
- HTML Standard: Try to upgrade an element, WHATWG.
- DOM Standard: Insert, WHATWG.
- CustomElementRegistry: upgrade() method, MDN.
- HTML Standard: The upgrade() method, WHATWG.
- Why does customElements.upgrade appear to not upgrade this custom element?, Stack Overflow.
- CustomElementRegistry: whenDefined() method, MDN.
- CustomElementRegistry::whenDefined() in custom_element_registry.cc, at Chromium 158.0.8127.18, Chromium.
- CustomElementRegistry: get() method, MDN.
- CustomElementRegistry: getName() method, MDN.
- Custom Elements v1: Element upgrades, Eric Bidelman, web.dev.
- Modern Web Guidance: Custom Elements, Upgrade timing and :defined, Chrome for Developers.
Coming next: Properties set before the upgrade. A property set too early hides your setter. Learn the pattern that fixes it.