Detecting when a Web Component is loaded with CSS
Over the last week or so, I’ve been writing about why Web Components are awesome.
Today, I wanted to share an awesome little trick Hawk Ticehurst taught me over on Mastodon.
The CSS :defined
pseudo-class applies to an element when it’s been defined in the browser. For Web Components, that doesn’t happen until the customElements.define()
method has been run on your custom element.
<!-- This is a counter button -->
<count-up></count-up>
// The <count-up> element receives the :defined pseudo-class when this JS method runs
customElements.define('count-up', class extends HTMLElement {
// ...
});
I’m a big fan of HTML Web Components, custom elements that progressively enhanced existing functional HTML.
But sometimes, a Web Component will only work with JavaScript and won’t work until its been defined.
👋 Quick aside: if you want to learn how to create your own Web Components, I have 17 lessons, a workshop, a handful of projects, and tons of demos over at the Lean Web Club. Today only, you can join for less than $5/month, or just $45 for a whole year!
Historically, I’ve added a [hidden]
attribute to the custom element, and removed it as part of the instantiation process in the constructor()
method for my Web Component class.
<!-- Hide it by default -->
<count-up hidden></count-up>
// Show it when the element is instantiated
customElements.define('count-up', class extends HTMLElement {
constructor () {
super();
this.removeAttribute('hidden');
}
});
But the :defined
pseudo-class provides another way to do this using just CSS instead of JavaScript.
/* Hide the <count-up> element until it's defined */
count-up:not(:defined) {
display: none;
}