Web Components API in a Nutshell

The what and why for the native Web Components API

We all know that re-using code as much as possible is generally a good idea. Sharing code between components saves us money, energy, and, most importantly, time.

Re-using code hasn’t been so easy for the complex HTML. You’ve sometimes had to write to render custom UI controls, and using them multiple times can turn your page into a mess if you are not careful.

Here’s where Web Components come in. Web Components is a suite of different technologies which allow you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and to utilize them in your web apps.

For example, web components let us define custom elements in HTML files.

Custom <app-button> HTML element (not JSX)

Note; We’re not using webpack, rollup, or bundler above. The syntax is supported by HTML5 and JavaScript. If you want to learn native JavaScript, I recommend reading the “Eloquent JavaScript” book.

Each JS framework has its own API for reusable components. A react-video-player won’t work in Ember, and a ember-preload won’t work in Vue. For example, Matrix.org’s JavaScript SDK is tied to React. Other JS SDK’s use an iframe (Facebook Like Button and other ad-tech SDK’s usually go this route) or abstain from providing any UI functionality at all (like WebTorrent).

Web Components, since they act exactly like built-in HTML elements, should work within any framework. If your framework can render arbitrary HTML elements, then it can render a custom HTML element. If you’re just building an app, it doesn’t matter; just render the HTML that you want in your template language. As a library author, the ability to provide a JavaScript widget with some level of encapsulation using only browser built-in APIs seems really nice. — notriddle