What are web components?

Chances are, by now, you’ve seen discussion of web components or heard this buzz-word floating around. Developers are excited to tap into what they have to offer, but you might be asking yourself, “What exactly are web components?” At a high level, they are HTML tags that are defined by developers. For instance, if you wanted to create a tag that placed a youtube video player into a page, you could define a tag like <youtube-player></youtube-player> which automatically embeds the player into your page.

If we take a moment to dive into the concept a little further, web components are actually comprised of four different browser features.

  1. Custom Elements
  2. Templates
  3. HTML Imports
  4. The Shadow DOM

Custom elements are what we see on the surface. These are the custom tags that the browser recognizes and executes customized code for. Not all browsers understand how to recognize these, but it is a critical feature.

Templates and HTML Imports represent how web components are defined and incorporated into a web page. A template is a file that consists of HTML, CSS, and Javascript, which is then imported into the web page to ensure that custom elements are presented correctly.

The Shadow DOM is an interesting part of web components. While custom elements are understood as instances of a template for the component, the underlying HTML is hidden from view. Many current browsers actually utilize the Shadow DOM for common tags such as <video> and the hidden markup can be revealed by adjusting your browser settings.

So what makes web components useful going forward? For one thing, they align nicely with the DRY principle. You won’t need to repeatedly use code to replicate UX across your app. It also provides a clear separation of responsibilities. Each component has its own Javascript and CSS that cannot be interfered with by other parts of the page. As a result, web components don’t require a lot of overhead to integrate with your existing app. They don’t have to be “wired in” with the existing code; they stand independently.

So why don’t we see them used more commonly yet? Well, as I alluded to earlier with custom elements, not every browser supports all of the features required for web components. But there are a couple of options for emulating the functionality in older browsers. They’re referred to as polylibs (similar to polyfills) and the most popular of these libraries are Google’s Polymer and Mozilla’s X-tag. You can also use frameworks like AngularJS and React to emulate web component functionality (though they are not strictly web components.)

Below, we have the example web component I described at the start of the post. Using X-Tag, we’ve created a web component that displays the youtube player with minimal markup and javascript.

You can read more about web components at webcomponents.org and x-tags.org.