Web Components are portable, reusable, bundled units of HTML, JavaScript and CSS. An existing Web Component can be used without writing new code, simply by adding an import statement to an HTML page.
Imports - support bundling html, javascript and CSS files
<template><p>This is a template!</p></template>
<template id="my-template">
<p>This is a template!</p>
</template>
<script> var temp = document.querySelector('#my-template'); var clone = document.importNode(temp.content, true); document.body.appendChild(clone); <script>
Inject data before cloning by manipulating the template clone
1. Get a reference to the template var template = document.querySelector('template'); 2. Use document.importNode to clone the template's content var clone = document.importNode(template.content, true); 3. Change the target element within the template as desired clone.querySelector('.adjective').textContent = 'neat'; 4. Append element to page document.body.appendChild(clone);
Manually clone both parent and child templates if templates are nested
<template id="outer-template"> <template id="inner-template"><p>This is a template!</p></template> </template> <script> var outerTemplate = document.querySelector(#outer-template); var innerTemplate = document.querySelector(#inner-template); var outerClone = document.importNode(template.content); var innerClone = document.importNode(template.content); document.body.appendChild(outerClone); document.outerClone.appendChild(innerClone); <script>
Two core functionalities:
1. Define your own HTML element (name must have a
dash - think of the first dash as a namespace)
2. Extend existing elements by adding an 'is' attribute
<input type="text" is="search">
<ek-lego-car />
1. Create a prototype for the custom element
var LegoCar = Object.create(HTMLElement.prototype);
// Add properties and functions to prototype here
2. Register the element via registerElement
document.registerElement('lego-car');
3. Use it: Add to DOM or place tag on the page
document.body.appendChild(new LegoCar()); or <lego-car>
Shadow DOM provides encapsulation for the JavaScript, CSS, and templating in a Web Component. A Shadow DOM makes it so these things remain separate from the DOM of the main document. A Shadow DOM must always be attached to an existing element.
Add elements
<template>
<h1>Hello from the shadow DOM!</h1>
</template>
<div id="host>
<script>
var host = document.querySelector('template');
var root = host.createShadowRoot();
root.appendChild(document.importNode(template.content, true));
</script>
</div>
<link rel="import" href="component.html" />
Check out Polymer!