Styling undefined elements with :defined
Use the :defined CSS selector to style web components before their JavaScript loads, fix the flash of undefined custom elements (FOUCE), and stop layout shift.
- 01Spot an undefined elementSay what the browser shows for a tag before its class arrives, and which elements
:definedmatches. - 02Hide the wait safelyHide waiting tags with
:not(:defined)so they still show if the script fails, for one tag or a whole section. - 03Stop the jumpKeep a component's room while it waits, so nothing on the page moves when it arrives, and check it in Chrome.
What happens before a web component is defined?
Ravi's menu page for Leaf and Kettle is finished. He themed it in the last lesson. The owner opens it on her phone, on a train with a weak signal. For a moment, the menu is a row of plain words: Green tea Brew for 3 minutes. Price: 4 Add to order. Then a card snaps into place around them, with a real button. The opening hours under it jump down, just as she reaches for them.
She asks Ravi two things. Why does the page do that? And can he stop it?
Before a custom element's JavaScript arrives, the browser shows the tag as a plain element: just its text, with no box and no styles. The CSS :defined selector matches an element once its class is registered. So :not(:defined) lets you hide waiting tags, or give them their final size. Then the page doesn't flash or jump.
Here is Ravi's card, with Web Awesome's loader held back until you click:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"> <wa-card> <strong slot="header">Green tea</strong> Brew for 3 minutes. Price: 4 <wa-button slot="footer" variant="brand">Add to order</wa-button></wa-card><p>Open every day, 8 to 6.</p><button>Add the loader</button> <script> document.querySelector("button").addEventListener("click", () => { const loader = document.createElement("script"); loader.type = "module"; loader.src = "https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"; document.head.append(loader); });</script>- Line 1 is the stylesheet line from lesson 2.1. The loader line is missing on purpose.
- Lines 3 to 7 are the menu card: a header, a line of text, and a button in the footer.
- Line 8 is a note under the card. Line 9 is a plain button.
- Line 12 waits for a click. Then lines 13 to 16 make a new
<script>element with the loader's address, and add it to the page. It's the loader line from lesson 2.1, arriving late, as on a slow network.
Before you click, the result shows plain words in a row. Click Add the loader. The loader defines wa-card and wa-button. The browser upgrades both tags in place, as in lesson 1.1. A card appears, with a blue button, and the note jumps down.
Two things went wrong for the owner. First, she saw the page half built: a flash of plain words that then changed. Second, the page jumped. Both happen for one reason. The HTML arrives before the JavaScript that defines its tags.
Leaf and Kettle opens at 8. The van with the tables comes at 8:05. For five minutes, early customers stand around bare boxes, with their cups on top. Then the staff carry the tables in, and everyone has to step aside.
- In real life: The café's doors opening at 8
- In JavaScript: The browser showing the page's HTML
- In real life: Cups set down on bare boxes
- In JavaScript: Tags showing their text, with no styles
- In real life: The van with the tables
- In JavaScript: The component's JavaScript, arriving late
- In real life: Staff setting up tables around the customers
- In JavaScript: The browser upgrading tags in front of the reader
- In real life: Everyone stepping aside
- In JavaScript: The note jumping down: a layout shift
A custom element looks like plain text until its class is registered. :defined matches it once it is. Use :not(:defined) to hide the waiting tag, with a time limit. Or use it to give the tag the room it will need.
This lesson takes the two problems one at a time. First, what a waiting tag is, and how :defined sees it. Then how to hide the wait safely. Then how to keep the page still.
What is an undefined custom element?
An undefined element is a tag with a valid custom element name, like tea-card, whose class isn't registered yet. The browser keeps it, as lesson 1.1 showed. But what is it, while it waits? This page asks:
<tea-card>Green tea. Brew for 3 minutes.</tea-card><teacard>Black tea. Brew for 4 minutes.</teacard> <script> const card = document.querySelector("tea-card"); const unknown = document.querySelector("teacard"); console.log(card.constructor.name); console.log(unknown.constructor.name); console.log(getComputedStyle(card).display); console.log(card.matches(":defined")); console.log(unknown.matches(":defined"));</script>- Line 1 uses
<tea-card>, a name with a hyphen. Nothing on this page defines it. - Line 2 uses
<teacard>, with no hyphen. It can never be a custom element. - Lines 5 and 6 find the two tags.
- Line 7 prints the waiting tag's class:
HTMLElement. That's a plain HTML element, the class every custom element extends. - Line 8 prints
HTMLUnknownElement. A tag with no hyphen is an unknown element: a tag HTML doesn't know, and never will. - Line 9 prints
inline. The browser has no CSS fortea-cardyet. So it lays the tag out like a<span>: inside the line of text, with no box of its own. - Line 10 prints
false: the waiting tag doesn't match:defined. Line 11 printstrue: the unknown tag does.
The result shows both sentences run together, like words in one paragraph. That's the plain look from the first example. A waiting tag has no class of its own yet, no shadow root, and no styles. It only has the text you wrote inside it. Why it matters: whatever you put between the tags is what readers see while the script loads.
Every element has a state
Every element keeps a value the DOM Standard calls its custom element state. It's like a sticker that says how far along the element is. There are five:
undefined: a custom element waiting for its class.custom: upgraded. Its class has run.failed: its constructor threw while the browser was creating it, withcreateElement()or the HTML parser.precustomized: its constructor is running during an upgrade. If that constructor throws, the element stays in this state for good.uncustomized: every other element. That means built-in tags like<p>, and unknown tags like<teacard>.
:defined reads that sticker. The HTML Standard says it matches any element that is defined. The DOM Standard says an element is defined when its state is uncustomized or custom.
:defined reads one value on every element: its state. Only a custom element that is still waiting, or whose upgrade failed, doesn't match.When the upgrade fails
An upgrade that fails needs a closer look. Here, the class's constructor throws an error on purpose:
<tea-card>Green tea. Brew for 3 minutes.</tea-card> <script> class TeaCard extends HTMLElement { constructor() { super(); throw new Error("The card broke"); } } customElements.define("tea-card", TeaCard); const card = document.querySelector("tea-card"); console.log(customElements.get("tea-card") === TeaCard); console.log(card.matches(":defined"));</script>- Lines 4 to 9 make a class whose constructor throws.
- Line 11 registers it. The browser tries to upgrade the tag on line 1, and the constructor throws.
- Line 13 prints
true: the registry has the class. - Line 14 prints
false: the tag doesn't match:defined.
The result shows the error, Error: The card broke. The registry has a class for tea-card. But this tag's upgrade failed, so its state stays precustomized. The browser never runs its constructor again, so it stays a plain element for good. Why it matters: a rule that hides waiting tags would hide a failed one forever. You'll fix that with a fallback.
How does the :defined CSS selector work?
:defined is a pseudo-class: a selector for a state an element is in, like :hover. On its own, it matches every element that is defined. Put a tag name in front, and it only matches that tag. Wrap it in :not(), and it matches the tags still waiting:
<style> tea-card:not(:defined) { color: gray; } tea-card:defined { color: green; }</style> <tea-card>Green tea. Brew for 3 minutes.</tea-card><button>Define tea-card</button> <script> const card = document.querySelector("tea-card"); console.log(card.matches(":defined")); document.querySelector("button").addEventListener("click", () => { customElements.define("tea-card", class extends HTMLElement {}); console.log(card.matches(":defined")); }, { once: true });</script>- Line 2 colors
tea-cardgray while it isn't defined. - Line 3 colors it green once it is.
- Line 11 prints
false. Nothing has definedtea-cardyet. - Lines 12 to 15 add a listener for the first click only.
{ once: true }removes it after it runs, because a seconddefine()for the same name would throw. - Line 13 defines
tea-cardwith an empty class. Line 14 printstrue.
Before the click, the words are gray. Click Define tea-card. They turn green at once, and the console prints true. You never changed a class or a style. The element's state changed, and the browser matched the rules again. Why it matters: every fix in this lesson uses this one switch.
New staff at Leaf and Kettle wear a trainee badge. The manager has one rule: trainees work in the back room. The day their training ends, the badge comes off, and the rule stops applying. Nobody rewrites the rule. Staff who came already trained never wore a badge.
- In real life: The trainee badge
- In JavaScript: The
undefinedstate - In real life: The rule: trainees work in the back room
- In JavaScript:
tea-card:not(:defined) { … } - In real life: Training ends, and the badge comes off
- In JavaScript:
define()upgrades the tag, and it matches:defined - In real life: Staff who came already trained
- In JavaScript: Built-in tags like
<p>, always defined
Read each row across: the element, its state, and whether it matches.
| The element | Its state | Does it match :defined? |
|---|---|---|
<p> | A built-in element. Its state is uncustomized. | Yes, always. |
<teacard> | An unknown element, because its name has no hyphen. Its state is uncustomized. | Yes, always. |
<tea-card> before define() | A custom element waiting for its class. Its state is undefined. | No. |
<tea-card> after define() | It was upgraded. Its state is custom. | Yes. |
<tea-card> whose constructor threw | The upgrade failed. Its state stays precustomized. | No, and it never will. |
Two rows surprise people. <teacard> matches :defined, so teacard:not(:defined) would never hide it. And a failed tea-card never matches, even though the registry has its class.
What is FOUCE, the flash of undefined custom elements?
In 2021, Cory LaViska, who created Shoelace, gave the plain-words moment a name. He called it FOUCE, a flash of undefined custom elements, and says it rhymes with "spouse". It's a cousin of FOUC: the flash of unstyled content you get when a page shows before its stylesheet loads.
Why does it happen? Web Awesome's loader is a module script. The browser runs it after it has read the HTML. Then the loader fetches each component's file, as lesson 2.1 showed. The browser doesn't wait for any of that. It paints the page as soon as it can, with the tags still waiting.
Sometimes the flash is fine. A tea-label that shows Green tea, then Green tea: brew for 3 minutes, stays readable the whole time. Jim Nielsen builds components this way on purpose. He writes good HTML first, and the script only adds to it. Then there is nothing to hide. Hide the wait when the waiting tag looks broken, like Ravi's row of words.
The examples from here on use a small version of the kit's card, in its own file:
class TeaCard extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: "open" });
shadow.innerHTML = `
<style>
:host {
display: block;
box-sizing: border-box;
min-block-size: 6rem;
padding: 12px;
border: 2px solid #00883c;
border-radius: 8px;
}
</style>
<slot></slot>`;
}
}
customElements.define("tea-card", TeaCard);- Line 4 gives the card a shadow root.
- Lines 7 to 14 style the card itself, with
:host. Line 8 makes it a block. Line 9 counts the padding and the border inside its size. Line 10 makes it at least 6rem tall. - Line 16 is a slot. It shows the words you put inside
<tea-card>. - Line 20 registers it.
The playground loads this file three seconds late. Pick a rule for the waiting card. Each choice starts a fresh page, so watch the first three seconds:
<style> /* No rule for undefined tags */ @keyframes show-anyway { to { opacity: 1; } }</style> <tea-card>Green tea. Brew for 3 minutes.</tea-card><p>Open every day, 8 to 6.</p> <script type="module"> setTimeout(() => import("./tea-card.js"), 3000);</script>For three seconds you see the plain words. Then the green card appears around them, and the note jumps down. That change, in front of the reader, is the flash.
Three of the rules hide the words, in different ways. Read each row across: the rule, then what happens to the waiting words.
| How you hide it | Does it keep its space? | Can screen readers read it? | What if the script never arrives? |
|---|---|---|---|
visibility: hidden | Yes, the line it took. | No. | It stays hidden for good. |
display: none | No. Things below it move up. | No. | It stays hidden for good. |
opacity: 0 with a 2 s animation | Yes, the line it took. | Yes. | It shows after 2 seconds. |
visibility: hidden and display: none take the words away from screen readers too. MDN's page on visibility warns about this. And neither comes back if the script fails. opacity: 0 only makes the words see-through, so screen readers can still read them. The animation brings them back after two seconds, no matter what.
Hide it with a fallback
Chrome's guidance for custom elements says to hide waiting tags so that you fail open. That means: if the script never loads, the content shows anyway. Here is the rule on its own, on a page whose script never comes:
<style> tea-card:not(:defined) { opacity: 0; animation: show-anyway 0s 2s forwards; } @keyframes show-anyway { to { opacity: 1; } }</style> <tea-card>Green tea. Brew for 3 minutes.</tea-card><p>Open every day, 8 to 6.</p>- Line 2 picks every
tea-cardthat isn't defined. - Line 3 makes it see-through.
- Line 4 starts an animation called
show-anyway. It takes0s, and it starts after2s.forwardskeeps its last frame when it ends. - Lines 6 to 8 are the animation's keyframes. Its one frame,
to, setsopacityto 1. - Line 11 is the card. Nothing on this page ever defines it.
Press Run again on the result, and count. For two seconds, only the note shows. Then the words appear, though the card never arrives. If the script does arrive in time, the tag becomes defined. Line 2 stops matching, and the rule and its animation go away.
The cook at Leaf and Kettle won't send out a cake while the cream is still on its way. A half-finished cake looks wrong. But the waiter has a rule. If the cream isn't there in two minutes, serve the cake plain. A plain cake beats no cake.
- In real life: The cake waiting in the kitchen
- In JavaScript:
opacity: 0on the waiting tag - In real life: The cream arriving
- In JavaScript: The script defining the tag
- In real life: Serving it plain after two minutes
- In JavaScript: The animation that sets
opacityto 1 after 2 seconds - In real life: A cake that never leaves the kitchen
- In JavaScript:
visibility: hiddenwith no fallback
Why it matters: a script can fail for many reasons. The network drops, an address has a typo, or a constructor throws. With a fallback, your readers still get the words.
How do you wait for several web components at once?
Hiding each tag on its own has a catch, which Cory LaViska noticed too. The tags appear one by one, as each file arrives. Ravi's menu would build itself piece by piece. It's better to show the menu once, when everything in it is ready.
But don't hide the whole page. Chrome's guidance warns about one slow, unimportant widget, like a share button. It would hold back everything. Hide just the part that needs it. CSS can do that alone, with :has(). :has() matches an element that contains something matching the selector in its brackets:
<style> .menu:has(:not(:defined)) { opacity: 0; animation: show-anyway 0s 2s forwards; } @keyframes show-anyway { to { opacity: 1; } }</style> <h1>Today's tea</h1><div class="menu"> <tea-card>Green tea. Brew for 3 minutes.</tea-card> <tea-price amount="4"></tea-price></div><p>Open every day, 8 to 6.</p> <script type="module"> setTimeout(() => import("./tea-card.js"), 1000); setTimeout(() => import("./tea-price.js"), 1500);</script>- Line 2 picks the
.menuwhile it holds any tag that isn't defined. - Lines 3 to 6 are the rule from the last section: see-through, for two seconds at most.
- Line 9 is a heading, outside the menu. Line 14 is the note.
- Lines 10 to 13 are the menu: a
tea-cardand atea-price. Thetea-price.jstab is the kit's price tag from lesson 1.4. - Lines 17 and 18 load the card after one second, and the price after one and a half.
Press Run again. The heading and the note show at once. The menu stays hidden until both tags are defined, at 1.5 seconds. Then the card and Price: 4 appear together.
Waiting with whenDefined()
You can do the same in JavaScript, with customElements.whenDefined() from lesson 2.2. MDN's page uses it this way: it shows a menu only when the tags inside are ready.
<style> .waiting { opacity: 0; }</style> <div class="menu waiting"> <tea-card>Green tea. Brew for 3 minutes.</tea-card> <tea-price amount="4"></tea-price></div> <script type="module"> setTimeout(() => import("./tea-card.js"), 1000); setTimeout(() => import("./tea-price.js"), 1500); const names = ["tea-card", "tea-price"]; const tags = names.map((name) => customElements.whenDefined(name)); const tooLate = new Promise((resolve) => setTimeout(resolve, 3000)); await Promise.race([Promise.allSettled(tags), tooLate]); document.querySelector(".menu").classList.remove("waiting"); console.log("The menu is showing.");</script>- Line 2 makes anything with the class
waitingsee-through. Line 5 gives the menu that class. - Lines 11 and 12 load the two files late, as before.
- Line 15 asks for one promise per name. Each one fulfills when its name is defined.
- Line 16 makes a promise that fulfills after three seconds.
- Line 17 waits for whichever comes first.
Promise.allSettled()waits until every promise has settled, so it fulfills when both tags are defined.Promise.race()settles as soon as the first of its promises does. - Line 18 removes
waiting. Line 19 printsThe menu is showing.
The menu appears at 1.5 seconds, and the console prints The menu is showing. Now change 1500 on line 12 to 5000. The price is late, but the timer wins. The menu shows at three seconds, and the price fills in at five.
Why the timer? A tag that's never defined never settles its promise. A typo in a name is enough. Without the race, the menu would stay hidden for good. Cory LaViska added the same two-second race to his own fix in 2024.
Why allSettled(), and not Promise.all()? Promise.all() stops at the first promise that fails, and whenDefined() fails at once for a name with no hyphen. allSettled() keeps waiting for the rest. Both are explained in Promise combinators.
Four friends book a table at Leaf and Kettle for 7:00. The host seats them together when the last one walks in. But at ten past, the host seats whoever is there and brings the menus. Nobody waits by the door all night for a friend who isn't coming.
- In real life: Each friend walking in
- In JavaScript: Each
whenDefined()promise fulfilling - In real life: Seating them once all four are in
- In JavaScript:
Promise.allSettled() - In real life: Ten past seven
- In JavaScript: The three-second timer
- In real life: Whichever comes first
- In JavaScript:
Promise.race()
Web Awesome's wa-cloak class
Web Awesome has this built in. Its stylesheet hides nothing by itself: in the first example, the waiting tags showed their words. But it has a class for the job, wa-cloak. Here is its rule, from the stylesheet Ravi already loads:
.wa-cloak:has(:not(:defined)) {
animation: 2s step-end wa-fouce-cloak;
}
@keyframes wa-fouce-cloak {
from { opacity: 0; }
to { opacity: 1; }
}- Line 1 picks any element with the class
wa-cloakwhile it holds a waiting tag, like your.menurule. - Line 2 runs an animation for 2 seconds.
step-endholds the first frame until the very end. So the element stays see-through, then shows. - Lines 5 to 8 are the frames: from see-through to fully shown.
The loader adds the second half. Once it has loaded every tag it found, or after two seconds, it removes wa-cloak from every element. Web Awesome's docs suggest putting the class on a wrapper, or on <html> for the whole page. Ravi follows Chrome's advice and puts it on his menu only.
How do you stop web components from causing layout shift?
Hiding fixes the flash. It doesn't fix the jump. In the hiding playground, the note jumped with every rule. A waiting tag takes the room of its words. The card needs more, so it pushes everything under it down.
When something you can see moves without you asking, that's a layout shift. Chrome adds these up into Cumulative Layout Shift (CLS), one of the Core Web Vitals. The web performance course explains how CLS is scored. Here, you only need to see Chrome notice the jump:
<tea-card>Green tea. Brew for 3 minutes.</tea-card><p>Open every day, 8 to 6.</p> <script type="module"> const observer = new PerformanceObserver((list) => { for (const shift of list.getEntries()) { console.log(`Layout shift, score ${shift.value.toFixed(3)}`); } }); observer.observe({ type: "layout-shift" }); setTimeout(() => import("./tea-card.js"), 1000);</script>- Lines 5 to 9 make a PerformanceObserver: an object the browser calls with performance entries as it records them.
- Line 10 asks for
layout-shiftentries. - Line 7 prints each shift's score. The score grows with how much moved, and how far.
- Line 11 loads
tea-card.jsafter one second.
About a second after the page loads, the console prints one line: Layout shift, score and a number above 0. The number depends on the size of the result. Only Chromium browsers, like Chrome and Edge, report layout shifts this way.
The fix is to keep the card's room while it waits. You know tea-card will be at least 6rem tall: line 10 of tea-card.js says so. Give the waiting tag the same size. The playground below measures the jump:
- Line 2 is the rule you pick.
- Line 10 measures where the note's top edge is, before the card arrives.
getBoundingClientRect()gives an element's position and size on the screen. - Line 12 loads
tea-card.jsone second later.awaitwaits until it has run. - Lines 13 and 14 measure again, and print the difference in whole pixels.
<style> /* Nothing reserved */</style> <tea-card>Green tea. Brew for 3 minutes.</tea-card><p>Open every day, 8 to 6.</p> <script type="module"> const note = document.querySelector("p"); const before = note.getBoundingClientRect().top; setTimeout(async () => { await import("./tea-card.js"); const after = note.getBoundingClientRect().top; console.log(`The note moved ${Math.round(after - before)}px.`); }, 1000);</script>Before the card arrives, the words take one line, about 18px tall. The card is 6rem, which is 96px. So the note moves down by the difference, about 78px. The exact number depends on your browser's font.
Only the exact size stops the jump. The waiting tag becomes a block 6rem tall, with its words at the top. When the class arrives, the card takes the same 6rem. The console prints The note moved 0px. Put the same rule in the layout shift example above, and its console stays empty: Chrome sees no shift at all.
Why :not(:defined), and not a plain tea-card rule? Once the card is defined, it sizes itself with :host. A page rule on the element itself beats :host, as lesson 2.3 showed. With :not(:defined), your rule steps aside the moment the card's own styles arrive.
Ravi's friend says she'll come at noon. He puts a "Reserved" card on the chair next to him, so the table is set for two from the start. When she arrives, she sits down. Nobody at the table has to move their cups.
- In real life: The reserved card on the chair
- In JavaScript:
tea-card:not(:defined) { display: block; min-block-size: 6rem; } - In real life: The friend arriving
- In JavaScript: The class arriving and upgrading the tag
- In real life: Nobody moving their cups
- In JavaScript: The note staying put: no layout shift
- In real life: A chair too small for her
- In JavaScript:
min-block-size: 3rem: the note still moves
When the height follows the width
Some components change height with their width, like a photo that keeps its shape. For those, keep a shape instead of a height, with aspect-ratio:
<style> tea-photo:not(:defined) { display: block; aspect-ratio: 16 / 9; background: #e3f4e8; }</style> <tea-photo></tea-photo><p>Open every day, 8 to 6.</p>- Line 2 picks the waiting
tea-photo. Nothing defines it on this page. - Line 3 makes it a block, as wide as the page.
- Line 4 makes its height 9/16 of its width.
- Line 5 tints it pale green, so you can see the room it keeps.
The result shows a pale green box with a 16 by 9 shape. Make the window narrower, and the box keeps its shape. For images, ads, and other late content, see Fixing layout shifts.
Fix the flash on Leaf and Kettle's menu
Ravi now has two tools. He can hide the wait, with a fallback. And he can keep the room. First, sort each part of a page by what it needs:
- A
wa-dialogwhose text would sit on the page until its script arrives - A card whose words run together in a jumble until its script arrives
- A
tea-cardthat is always 6rem tall, with a note under it - A photo component whose height follows its width
- A
tea-labelthat shows Green tea, then Green tea: brew for 3 minutes - A link inside a
<tea-share>tag that already works as a plain link
Sort each tag by what it needs while its script loads.
Here is Ravi's menu page, fixed. The loader arrives one second late again. It stands in for the owner's train:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"> <style> .menu { min-block-size: 16rem; } wa-dialog:not(:defined) { display: none; }</style> <h1>Today's tea</h1><div class="menu wa-cloak"> <wa-card> <strong slot="header">Green tea</strong> Brew for 3 minutes. Price: 4 <wa-button slot="footer" variant="brand" data-dialog="open thanks">Add to order</wa-button> </wa-card></div><p>Open every day, 8 to 6.</p> <wa-dialog id="thanks" label="Thank you"> Your tea is on its way to the counter.</wa-dialog> <script> setTimeout(() => { const loader = document.createElement("script"); loader.type = "module"; loader.src = "https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"; document.head.append(loader); }, 1000);</script>- Line 1 is the stylesheet line from lesson 2.1.
- Line 4 gives the menu at least 16rem of height from the start. The card needs a little less, so nothing under it moves when it arrives.
- Line 5 hides the thank-you dialog until it's defined. A waiting
wa-dialogwould show its words on the page. A closed dialog takes no room, sodisplay: noneis safe here. - Line 9 puts
wa-cloakon the menu only. The heading and the note aren't hidden. - Lines 10 to 14 are the card. The button on line 13 opens the dialog.
- Lines 23 to 28 add the loader line from lesson 2.1, one second late. On Ravi's real page, it's the usual line in the
<head>.
Press Run again. For the first second, the heading and the note show, and the menu's spot is empty. Then the card appears, and the note doesn't move. The dialog's words never show on the page. Click Add to order to see them in the dialog. And if the loader never came, the menu would show its plain words after two seconds.
Open DevTools' Elements panel while it runs. The menu starts as <div class="menu wa-cloak">. Once the card is defined, the loader removes wa-cloak, and it's <div class="menu">.
Common mix-ups
- "Web Awesome's stylesheet hides undefined tags for you." No. It hides nothing until you add the
wa-cloakclass to an element. - "
:not(:defined)matches every tag the browser doesn't know." No. A name with no hyphen, like<teacard>, makes an unknown element, and it matches:defined. - "If the registry has the class, the element is defined." No. If its constructor threw, the upgrade failed, and the element never matches
:defined. - "
visibility: hiddenis a safe way to hide waiting tags." No. With no fallback, the words stay hidden if the script fails, and screen readers can't read them. - "Hide the
bodyuntil every tag is defined." No. One slow widget would then hold back the whole page. Hide only the part that needs it. - "Hiding a waiting tag stops the page from jumping." No. Hiding changes what you see, not the room the tag takes. Keep its room with
min-block-size. - "
whenDefined()gives up if the script fails." No. It waits forever. Race it against a timer.
Practice exercises
Answer first, then use the hints. Every result runs live, so you can check yourself.
What does the console print?
<p>Today's teas</p><teacup>Green tea</teacup><tea-card>Black tea. Brew for 4 minutes.</tea-card><tea-price amount="5"></tea-price> <script> const waiting = document.querySelectorAll(":not(:defined)"); console.log(waiting.length);</script>2. tea-card and tea-price are custom elements that nothing has defined. <p> is built in, and <teacup> has no hyphen, so both are defined.
This page's script never arrives, so the words stay hidden. Rewrite the rule so they show after two seconds anyway. Which property do you set to 0?
<style> tea-card:not(:defined) { visibility: hidden; }</style> <tea-card>Green tea. Brew for 3 minutes.</tea-card><p>Open every day, 8 to 6.</p><style> tea-card:not(:defined) { opacity: 0; animation: show-anyway 0s 2s forwards; } @keyframes show-anyway { to { opacity: 1; } }</style> <tea-card>Green tea. Brew for 3 minutes.</tea-card><p>Open every day, 8 to 6.</p>opacity. The animation waits two seconds, then sets opacity to 1, and forwards keeps it there. The words show even though the script never comes.
This card is taller than the lesson's. Fill in line 2 so the note doesn't move. What does the console print after your fix?
<style> /* Reserve the card's space here */</style> <tea-card>Green tea. Brew for 3 minutes.</tea-card><p>Open every day, 8 to 6.</p> <script type="module"> const note = document.querySelector("p"); const before = note.getBoundingClientRect().top; setTimeout(async () => { await import("./tea-card.js"); const after = note.getBoundingClientRect().top; console.log(`The note moved ${Math.round(after - before)}px.`); }, 1000);</script><style> tea-card:not(:defined) { display: block; min-block-size: 8rem; }</style> <tea-card>Green tea. Brew for 3 minutes.</tea-card><p>Open every day, 8 to 6.</p> <script type="module"> const note = document.querySelector("p"); const before = note.getBoundingClientRect().top; setTimeout(async () => { await import("./tea-card.js"); const after = note.getBoundingClientRect().top; console.log(`The note moved ${Math.round(after - before)}px.`); }, 1000);</script>The note moved 0px. This card is at least 8rem tall, so the waiting tag takes 8rem too. Before your fix, the note moved about 110px.
The menu never appears. Which name in the list is misspelled? Fix it, and add the three-second timer, so a typo can never hide the menu for good.
<style> .waiting { opacity: 0; }</style> <div class="menu waiting"> <tea-card>Green tea. Brew for 3 minutes.</tea-card> <tea-price amount="4"></tea-price></div> <script type="module"> setTimeout(() => import("./tea-card.js"), 1000); setTimeout(() => import("./tea-price.js"), 1500); const names = ["tea-card", "tea-prise"]; const tags = names.map((name) => customElements.whenDefined(name)); await Promise.allSettled(tags); document.querySelector(".menu").classList.remove("waiting"); console.log("The menu is showing.");</script><style> .waiting { opacity: 0; }</style> <div class="menu waiting"> <tea-card>Green tea. Brew for 3 minutes.</tea-card> <tea-price amount="4"></tea-price></div> <script type="module"> setTimeout(() => import("./tea-card.js"), 1000); setTimeout(() => import("./tea-price.js"), 1500); const names = ["tea-card", "tea-price"]; const tags = names.map((name) => customElements.whenDefined(name)); const tooLate = new Promise((resolve) => setTimeout(resolve, 3000)); await Promise.race([Promise.allSettled(tags), tooLate]); document.querySelector(".menu").classList.remove("waiting"); console.log("The menu is showing.");</script>tea-prise. Nothing ever defines it, so its promise never settles, and allSettled() waits forever. With the right name, the menu shows at 1.5 seconds. With the timer, a typo could only delay it three seconds.
This page loads Web Awesome's stylesheet but not its loader. In the script, print the name of each waiting tag, each name once, with commas between them. What does your line print?
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"> <wa-card> <strong slot="header">Green tea</strong> Brew for 3 minutes. <wa-button slot="footer" variant="brand">Add to order</wa-button></wa-card><wa-dialog label="Thank you">Your tea is on its way.</wa-dialog><wa-button>Brewing guide</wa-button> <script> // Print the name of each tag that's still waiting, each name once.</script><link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"> <wa-card> <strong slot="header">Green tea</strong> Brew for 3 minutes. <wa-button slot="footer" variant="brand">Add to order</wa-button></wa-card><wa-dialog label="Thank you">Your tea is on its way.</wa-dialog><wa-button>Brewing guide</wa-button> <script> const waiting = document.querySelectorAll(":not(:defined)"); const names = new Set([...waiting].map((element) => element.localName)); console.log([...names].join(", "));</script>wa-card, wa-button, wa-dialog, in the order they first appear. The Set drops the second wa-button. Web Awesome's loader starts the same way: it looks for waiting tags whose names start with wa-.
This page uses the real loader line. Pop it out, open DevTools, and in the Network panel tick Disable cache and set the throttling menu to 3G. Press Run again, and watch the menu's <div> in the Elements panel. Which class is gone once the card appears?
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <div class="menu wa-cloak"> <wa-card> <strong slot="header">Green tea</strong> Brew for 3 minutes. Price: 4 </wa-card></div>wa-cloak. The loader removes it once every tag it found is defined, or after two seconds. Until then, the cloak's rule kept the menu see-through.
Check your understanding
For each question, ask: is the tag defined yet, and what does the reader see and lose while it waits?
Question 1 of 8Which elements does
:not(:defined)match?Choose an answer to see the explanation.
Question 2 of 8What does this page's console print?
Read the code, then predict<teacup>Green tea</teacup> <script> const cup = document.querySelector("teacup"); console.log(cup.matches(":defined")); </script>Choose an answer to see the explanation.
Question 3 of 8A
tea-card's constructor throws while the browser upgrades it. What is true afterwards?Choose an answer to see the explanation.
Question 4 of 8This page never loads
tea-card.js. What does it show after five seconds?Read the code, then predict<style> tea-card:not(:defined) { visibility: hidden; } </style> <tea-card>Green tea. Brew for 3 minutes.</tea-card> <p>Open every day, 8 to 6.</p>Choose an answer to see the explanation.
Question 5 of 8Why race the
whenDefined()promises against a three-second timer?Choose an answer to see the explanation.
Question 6 of 8
tea-cardis 6rem tall once defined. Which rule keeps the note under it from moving?Choose an answer to see the explanation.
Question 7 of 8What does Web Awesome's
wa-cloakclass do?Choose an answer to see the explanation.
Question 8 of 8Why not hide the whole
bodyuntil every tag on the page is defined?Choose an answer to see the explanation.
Key takeaways
- An undefined element is a tag with a valid custom name and no class yet. It's a plain inline
HTMLElementthat shows only its text. :definedmatches built-in, unknown, and upgraded elements.:not(:defined)matches tags still waiting, and tags whose upgrade failed.- FOUCE is the flash of those waiting tags. It happens because the HTML arrives before the scripts that define its tags.
- Hide with
opacity: 0and a delayed animation, so the content shows anyway if the script fails. Avoidvisibility: hiddenwith no fallback. - Hide a section, not the whole page: use
:has(:not(:defined)), orwhenDefined()withPromise.allSettled()raced against a timer. Web Awesome'swa-cloakdoes both. - Hiding doesn't stop the jump. Give the waiting tag the size it will have, with
min-block-sizeoraspect-ratio.
Remember the one-liner.
A waiting tag is plain text: hide it with a time limit, and keep its room, so the page neither flashes nor jumps.
Sources
The facts on this page come from these specifications, docs, and posts:
- :defined, MDN.
- HTML Standard: the :defined pseudo-class, WHATWG.
- DOM Standard: custom element state, WHATWG.
- HTML Standard: upgrades, WHATWG.
- Custom Elements v1: unknown elements vs. undefined custom elements, Eric Bidelman, web.dev.
- Flash of Undefined Custom Elements (FOUCE), Cory LaViska.
- HTML Web Components: An Example, Jim Nielsen.
- Modern Web Guidance: Custom elements, upgrade timing and :defined, Chrome for Developers.
- visibility: Accessibility, MDN.
- Reducing FOUC with Web Components, Burton Smith.
- :has(), MDN.
- CustomElementRegistry: whenDefined(), MDN.
- Revisiting FOUCE, Cory LaViska.
- Reducing FOUCE, Web Awesome.
- LayoutShift, MDN.
- min-block-size, MDN.
- aspect-ratio, MDN.
Coming next: A preview of web components in frameworks and on servers. The same tag works in React, Vue, Angular, and Svelte, and in HTML sent from a server.