Web components are reusable client-side elements made using native code or third party libraries.
Web Components are W3C standard custom elements that can be reused in a page easily and encapsulate their scripts, templates and styles.
Some browsers still require one of more polyfill to work with Web Components.
web-component is for component written natively or with any library or framework. native-web-component is for native components only.
Web components rely on one or more of these browser features:
Custom Elements allow user defined elements to be created with an ES6 class that defines their behavior and functionality. For instance if you wanted to create
<my-element>
(naming convention is always at least 1 hyphen) for a class calledMyElement
you could call:customElements.define('my-element', MyElement);
Custom Elements are the only required portion of a Web Component.Shadow DOM allows a section of the page document to be a new, self-contained element. Styles and scripts do not cascade in or out by default, and the 'shadow' DOM (written by the component author) is kept separate from the 'light' DOM (written by the developer using the component).
<slot>
provides an insertion point for the light content.attachShadow()
allows a<template>
to be provided for the component's HTML.The
<template>
element enables chunk of markup to be use as a template to add content to the DOM. The markup in thetemplate
element is parsed but is not displayed and does not "run." For example, scripts in thetemplate
element are not executed. As of 2018 Web Components are moving away from HTML imports to ES6 Modules and the<template>
element is not used as often in JavaScript based components.ES6 Modules are currently the recommended mechanism for loading Web Components. Your component is now created in a JavaScript file and loaded using
import
statement.
Web Components are client side, but not all are user interface related. For instance web worker and IndexedDB clients can be written as components.