SJ (Scott Jehl)

Conditional Web Components are Perfect for Polyfills

photo of scott jehl profile headshot

By Scott Jehl

Yesterday, I released an HTML Web Component that makes responsive HTML video a little responsive-r. In short, the new (standard!) behavior of responsive video is great to have (and I'm a fan), but it falls a little short of many folks' expectations for truly responsive web design because it's only "responsive" at initial page load, and not after that. My Web Component patches that behavior, but only after checking that the browser doesn't already handle it on its own.

Planning for Obsolescence

In the article about the component, I called the pattern a Conditional Web Component, because depending on the browser's feature support, that web component might do something or nothing at all. To be clear, I'm not aware of any current plans for this behavior to be implemented natively in browsers. But it feels enough like the sort of thing that might be, one day, so I wanted to make sure my component plans for its own obsolescence accordingly. Indeed, I hope this behavior does work its way into browsers one day and my component can be yanked from delivery, but at the very least I want to make sure it does no harm if it's still there.

Making It Conditional

In my code, that condition happens at the end of the component script, right where the custom element gains its web component behavior. I wrote a feature test to see if the browser supports the functionality that the component will add (that test is an asynchronous function called videoMediaChangeSupport, which you can view here), and I call that function to decide whether to define the custom element's behavior or not.

In my case, it looks like this:

if( await videoMediaChangeSupport() === false ){
	customElements.define("responsive-video", ResponsiveVideo);

Now, that await bit is not important to the pattern itself, to be clear. Mine happened to be an asynchronous function, but it could just as easily look something like this:

if( myFeatureIsNotSupported ){
	customElements.define("responsive-video", ResponsiveVideo);

Anyway, using web components to write a polyfill in this way feels novel and appropriate to me, particularly for HTML elements. I'm interested in hearing if anyone else finds the same!