[Go Make Things] 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;  }

Here's a demo.

πŸ”₯ Cyber Monday Sale! Today only, save 50% on Lean Web Club membership, private coaching, and all of my courses and workshops. This sale ends today, so don't wait!

Cheers,
Chris

​

Want to share this with others or read it later? View it in a browser.​

​

Share :

Facebook Twitter Google+ Lintasme

Related Post:

0 Komentar untuk "[Go Make Things] Detecting when a Web Component is loaded with CSS"

Back To Top