Skip to main content

Command Palette

Search for a command to run...

WC-Upgrader module

Published
4 min read

WC-Upgrader module

If you haven’t heard yet, Web Components are here, most notably Custom Elements. We now have a platform API for defining our own HTML elements and composing them in our projects. While the platform API allows for us to write native components they still have to be loaded into the browser which brings us to a problem.

What’s the Problem?

If we have custom element markup in our application such as:<custom-element>Some Text as a child node</custom-element> the Some Text as a child node will be the only thing the browser understands on initial load. This means we can potentially have a bit of a repaint (likely including layout) like shown below.

A text node until it gets upgraded by the browser

A text node until it gets upgraded by the browser

I wanted to take a progressive enhancement approach to this problem of jitter with web components. The premise of the idea is that the HTML is already there in a base configuration and gets updated to something new. If we have an h1 element and do the same upgrade we get a much more pleasing result.

h1 Element getting upgraded to a custom-element

h1 Element getting upgraded to a custom-element

The other bonus to this approach is how it differs from popular JS libraries like React. If a user has Javascript disabled a react site won’t render (unless done so server side) but if we take this progressive enhancement approach our base content exists and then we can spice it up dynamically if possible.

OK, that was the why, what about the how?

WC-Upgrader is a JS Utility that ‘upgrades’ elements to the specified custom element when they are defined.

My initial approach was to initialize a custom-element and then set it’s innerHTML equal to that of the element needing to be upgraded and then delete it. This was a simple approach but had a nefarious bug. If you have elements getting upgraded and then parent elements getting upgraded, the child custom-elements will be re-appended to the DOM meaning their constructor will execute every time. If a component isn’t properly optimized you can quickly imagine how burdensome this could become.

The solution is a little more zesty in that we manually move the node tree from the old element to the custom element one child at a time to avoid constructors re-running when they don’t need to.

Yeah… I meant how do I use it…

It’s pretty simple as its still in its infancy as best practices around web components continue to involve. You can check out the git repo and start hacking in just a couple of minutes. Looking forward to hearing your thoughts on this approach!