Web Components standards consist of four main sections:
Custom elements section which allows you to create and define API of your own HTML elements. It would be really cool if we could create navigation by using one single tag and some super simple and declarative content inside, wouldn’t it?
Shadow DOM is an HTML encapsulation mechanism. Shadow DOM is a hidden tree of DOM nodes. These shadow DOM trees can be associated with an element, but do not appear as child nodes of the element. For instance,
<video> element. We place a single tag into our code and browser renders multiple elements like slider, volume controls, buttons and player window. Such elements are using Shadow DOM.
<template> element. The content of the
<template> element is parsed by the parser, but it doesn’t trigger scripts evaluation, downloading images, and so on. And, of course,
<template> element is not rendered.
HTML imports is a killer feature that allows all this functionality around web components to arrive to your HTML pages. This is an API which allows you to inject HTML fragments from external files into you HTML page, using the link tag:
<link rel="import" href="element.html" />
Support of the various standards that Web Components consist of is currently not as good to start using this features right a way. But chrome and opera teams are doing pretty good progress on that. Features support as for June 2014 was presented at Google I/O:
But that of course doesn’t mean that you can not use these technologies for building web components today! There are couple of teams at Chrome and Mozilla that are working on polyfill libraries which sneak support for Web Components into all modern browsers:
Polymer adds a new
<polymer-element> tag to the browser, which automatically turns templates into shadow DOM and registers custom elements for us. All we need to do is to tell Polymer what name to use for the tag and to make sure we include our template markup.
Bosonic is a sort of transpiler that takes Web Components in HTML files and transforms them into JS and CSS code, runnable on modern browsers. Bosonic uses some Polymer polyfills (Custom Elements, Mutation Observers and Weak Maps) and brings its own polyfills, including a powerful yet simple one for Shadow DOM.
Try it out
Web Components is a great concept that is going to change the way we build web apps and it is available for us today. By using any of polyfills libraries you can easily start playing with these technologies and give a feedback to those guys writing the specs which is really important. That’s the way we can tell how we would like these features to function before they are implemented, so that we don’t end up with some verbose and uncomfortable syntax.
Web components can be easily shared and reused in different projects. There are some amount of components written by community already, you can check them out or publish your own at customelements.io or component.kitchen