Componentes da Web

Componentes Web é uma suite de diferentes tecnologias que permite a criação de elementos reutilizáveis — com a sua funcionalidade encapsulada longe do restante código — E utilizá-las nas suas aplicações web.

Conceitos e utilização

Como programadores, todos sabemos que é boa ideia reutilizar código tanto como possível. Tradicionalmente, esta ideia não tem sido tão fácil para estruturas de marcação — pense no complexo HTML (e seus estilos e scripts associados) em que por vezes é necessário escrever controlos personalizados de UI e usá-los múltiplas vezes pode tornar a página numa desordem se não tiver cuidado

Componentes Web visa resolver tais problemas — consiste em três grandes tecnologias, que usadas em conjunto, permitem criar elementos versáteis com funcionalidade encapsulada e que podem ser reutilizados onde se queira sem medo de colisões de código.

  • Custom elements: A set of JavaScript APIs that allow you to define custom elements and their behaviour, which can then be used as desired in your user interface.
  • Shadow DOM: A set of JavaScript APIs for attaching an encapsulated "shadow" DOM tree to an element — which is rendered separately from the main document DOM — and controlling associated functionality. In this way, you can keep an element's features private, so they can be scripted and styled without the fear of collision with other parts of the document.
  • HTML templates: The <template> (en-US) and <slot> (en-US) elements enable you to write markup templates that are not displayed in the rendered page. These can then be reused multiple times as the basis of a custom element's structure.

The basic approach for implementing a web component generally looks something like this:

  1. Create a class or a function in which you specify your web component functionality. If using a class, use the ECMAScript 2015 class syntax (see Classes for more information). 
  2. Register your new custom element using the CustomElementRegistry.define() (en-US) method, passing it the element name to be defined, the class or function in which its functionality is specified, and optionally, what element it inherits from.
  3. If required, attach a shadow DOM to the custom element using Element.attachShadow() (en-US) method. Add child elements, event listeners, etc., to the shadow DOM using regular DOM methods.
  4. If required, define an HTML template using <template> (en-US) and <slot> (en-US). Again use regular DOM methods to clone the template and attach it to your shadow DOM.
  5. Use your custom element wherever you like on your page, just like you would any regular HTML element.


Using custom elements
A guide showing how to use the features of custom elements to create simple web components, as well as looking into lifecycle callbacks and some other more advanced features.
Using shadow DOM
A guide that looks at shadow DOM fundamentals, showing how to attach a shadow DOM to an element, add to the shadow DOM tree, style it, and more.
Using templates and slots
A guide showing how to define a reusable HTML structure using <template> (en-US) and <slot> (en-US) elements, and then use that structure inside your web components.


Elementos de Custom

CustomElementRegistry (en-US)
Contains functionality related to custom elements, most notably the CustomElementRegistry.define() (en-US) method used to register new custom elements so they can then be used in your document.
Window.customElements (en-US)
Returns a reference to the CustomElementRegistry object.
Life cycle callbacks
Special callback functions defined inside the custom element's class definition, which affect its behavior:
  • connectedCallback: Invoked when the custom element is first connected to the document's DOM.
  • disconnectedCallback: Invoked when the custom element is disconnected from the document's DOM.
  • adoptedCallback: Invoked when the custom element is moved to a new document.
  • attributeChangedCallback: Invoked when one of the custom element's attributes is added, removed, or changed.
Extensions for creating custom built-in elements
  • The is global HTML attribute: Allows you to specify that a standard HTML element should behave like a registered custom built-in element.
  • The "is" option of the Document.createElement() (en-US) method: Allows you to create an instance of a standard HTML element that behaves like a given registered custom built-in element.
CSS pseudo-classes
Pseudo-classes relating specifically to custom elements:
  • :defined (en-US): Matches any element that is defined, including built in elements and custom elements defined with CustomElementRegistry.define()).
  • :host (en-US): Selects the shadow host of the shadow DOM containing the CSS it is used inside.
  • :host() (en-US): Selects the shadow host of the shadow DOM containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host.
  • :host-context() (en-US): Selects the shadow host of the shadow DOM containing the CSS it is used inside (so you can select a custom element from inside its shadow DOM) — but only if the selector given as the function's parameter matches the shadow host's ancestor(s) in the place it sits inside the DOM hierarchy.

Shadow DOM

ShadowRoot (en-US)
Represents the root node of a shadow DOM subtree.
A mixin defining features that are available across document and shadow roots.
Element extensions
Extensions to the Element interface related to shadow DOM:
Relevant Node additions
Additions to the Node interface relevant to shadow DOM:
  • The Node.getRootNode() (en-US) method returns the context object's root, which optionally includes the shadow root if it is available.
  • The Node.isConnected (en-US) property returns a boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the Document object in the case of the normal DOM, or the ShadowRoot (en-US) in the case of a shadow DOM.
Event (en-US) extensions
Extensions to the Event interface related to shadow DOM:

Modelos de HTML

<template> (en-US)
Contains an HTML fragment that is not rendered when a containing document is initially loaded, but can be displayed at runtime using JavaScript, mainly used as the basis of custom element structures. The associated DOM interface is HTMLTemplateElement (en-US).
<slot> (en-US)
A placeholder inside a web component that you can fill with your own markup, which lets you create separate DOM trees and present them together. The associated DOM interface is HTMLSlotElement (en-US).
The slot global HTML attribute
Assigns a slot in a shadow DOM shadow tree to an element.
Slotable (en-US)
A mixin implemented by both Element and Text (en-US) nodes, defining features that allow them to become the contents of an <slot> (en-US) element. The mixin defines one attribute, Slotable.assignedSlot (en-US), which returns a reference to the slot the node is inserted in.
Element extensions
Extensions to the Element interface related to slots:
CSS pseudo-elements
Pseudo-elements relating specifically to slots:
The slotchange event
Fired on an HTMLSlotElement (en-US) instance (<slot> (en-US) element) when the node(s) contained in that slot change.


We are building up a number of examples in our web-components-examples GitHub repo. More will be added as time goes on.


Especificação Estado Comentário
HTML Living Standard
The definition of '<template> element' in that specification.
Living Standard The definition of <template> (en-US).
HTML Living Standard
The definition of 'custom elements' in that specification.
Living Standard The definition of HTML Custom Elements.
The definition of 'shadow trees' in that specification.
Living Standard The definition of Shadow DOM.
HTML Imports Working Draft Initial HTML Imports definition.
Shadow DOM Obsolete Initial Shadow DOM definition.

Compatibilidade de navegador

In general:

  • Web components are supported by default in Firefox (version 63), Chrome, and Opera.
  • Safari supports a number of web component features, but less than the above browsers.
  • Edge is working on an implementation.

For detailed browser support of specific features, you'll have to consult the reference pages listed above.

Consulte também

  • — site featuring web components examples, tutorials, and other information.
  • Hybrids — Open source web components library, which favors plain objects and pure functions over class and this syntax. It provides a simple and functional API for creating custom elements.
  • Polymer — Google's web components framework — a set of polyfills, enhancements, and examples. Currently the easiest way to use web components cross-browser.
  • — Easy Web Components in ~1kB Including polyfill — All you need is a browser and basic understanding of HTML, CSS, and JavaScript classes to be productive.
  • Slim.js — Open source web components library — a high-performant library for rapid and easy component authoring; extensible and pluggable and cross-framework compatible.
  • Smart.js — Web Components library with simple API for creating cross-browser custom elements.