Streamlining HTML web components
If you’re a front-end developer and you don’t read Chris Ferdinandi’s blog, you should change that right now. Add that RSS feed to your feed reader of choice!
Lately he’s been posting about some of the thinking behind his Kelp UI library. That includes some great nuggets of wisdom around HTML web components.
First of all, he pointed out that web components don’t need a constructor()
. This was news to me. I thought custom elements had to include this incantation at the start:
constructor () {
super();
}
But it turns that if all you’re doing is calling super()
, you can omit the whole thing and it’ll be done for you.
I immediately refactored all the web components I’m using on The Session. While I was at it, I implemented Chris’s bulletproof web component loading.
Now technically, I don’t need to do this. I’m linking to my JavaScript at the bottom of every page so I know it’s going to load after the HTML. But I don’t like having that assumption baked into my code.
For any of my custom elements that reference other elements in the DOM—using, say, document.querySelector()
—I updated the connectedCallback()
method to use Chris’s technique.
It turned out that there weren’t that many of my custom elements that were doing that. Because HTML web components are wrapped around existing markup, the contents of the custom element are usually what matters (rather than other elements on the same page).
I guess that’s another unexpected benefit to HTML web components. Because they’ve already got their own bit of DOM inside them, you don’t need to worry about when you load your markup and when you load your JavaScript.
And no faffing about with the dark arts of the Shadow DOM either.