When we discuss the context of the “browser wars” we often focus just on how one particular browser can get an edge on its competitors by developing or supporting a new feature. While the growing pains of this process have made designing for differing browsers sometimes tedious and unreliable, the war seems to finally be coming to an end and it’s time to reap the rewards.
As a result, the browser itself is becoming a developmental runtime like Node, and we’re seeing an explosion of new web tooling to support these new capabilities.
Web Components are made of different web technologies that allow you to create reusable custom elements, just like
<button> elements. These custom elements keep their functionality encapsulated away from the rest of the code, allowing them to just be dropped into any website.
The different technologies that make up Web Components are:
- HTML Templates: The
<slot>elements enable you to write markup templates that are not displayed in the rendered page. These can then be reused multiple times as the basis of a custom element’s structure. This essentially lets you “punch holes” in your component to let the native content of the page flow into or around your element.
The best part of Web Components is how simple they are to define and use. To instantiate a new component with a shadow DOM, you only have to do the following:
- Create a class or a function in which you specify your web component functionality.
- Register your new custom element using the
CustomElementRegistry.define()method, passing it the element name to be defined, the class or function in which its functionality is specified, and optionally, from which element it inherits.
- Attach a shadow DOM to the custom element using
Element.attachShadow()method. Then you can add child elements and event listeners to the shadow DOM using regular DOM methods.
- If needed, define an HTML template using
<slot>. Again, you’d use regular DOM methods to clone the template and attach it to your shadow DOM.
- Use your custom element wherever you like on your page, just like you would any regular HTML element.
In response to this new development environment with new potential, a group of open source developers have created open-wc, a collection of generators, frameworks, documentation, and tooling for creating Web Components.
They establish a list of best practices that can help you get your first component off the ground, and I’ve found their resources to be constantly growing and updating. This is a relatively new project, so it’s a great opportunity to jump aboard if you’re seeking a new open source community on the web frontier!
MDN: Web Components
Wikipedia: Browser wars
caniuse: Web Components