Web Components

A quick reference guide to Web Components for yours truly or anyone else who happens by. MDN is the source, as ever.

The four building blocks of Web Components are:

  • Custom Elements
  • HTML Template
  • HTML Import
  • Shadow DOM

Custom Elements

Custom Elements is a capability for creating your own custom HTML tags and elements. They can have their own scripted behavior and CSS styling. They are part of Web Components but they can also be used by themselves. Custom Elements raison d'etre is to provide lifecycle callbacks, which were not previously available.

Custom Elements Codepen

HTML Template

The HTML template element <template> is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.

Think of a template as a content fragment that is being stored for subsequent use in the document. While the parser does process the contents of the element <template> while loading the page, it does so only to ensure that those contents are valid; the element's contents are not rendered, however. Similar to the <defs> element in SVG.

HTML Template Codepen

Shadow DOM

Shadow DOM provides encapsulation for the JavaScript, CSS, and templating in a Web Component. Shadow DOM makes it so these things remain separate from the DOM of the main document. You can also use Shadow DOM by itself, outside of a web component.

Why would you want to keep some code separate from the rest of the page? One reason is that on a large site, for example, if the CSS is not carefully organized, the styling for the navigation can "leak" into the main content area where it was not intended to go, or vice-versa. As a site or an app scales, this kind of thing becomes difficult to avoid.

HTML Imports

HTML Imports is intended to be the packaging mechanism for Web Components, but you can also use HTML Imports by itself. Firefox won't be implementing as per below.

Mozilla will not ship an implementation of HTML Imports. We expect that once JavaScript modules — a feature derived from JavaScript libraries written by the developer community — is shipped, the way we look at this problem will have changed. We have also learned from Gaia and others, that lack of HTML Imports is not a problem as the functionality can easily be provided for with a polyfill if desired.

Resources

Google provides the required polyfill for HTML Imports and other Web Component goodies.

To keep up with developments check here -
http://jonrimmer.github.io/are-we-componentized-yet/