--- title: Componentes da Web slug: Web/Componentes_Web tags: - Artigo da Web - Componentes - Componentes da Web - Desenvolvimento da Web - Importações HTML - JavaScript - Landing - Modelo - Resumo - Sinopse - elementos personalizados - shadow dom - slot translation_of: Web/Web_Components ---
{{DefaultAPISidebar("Componentes 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.

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 {{domxref("CustomElementRegistry.define()")}} 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 {{domxref("Element.attachShadow()")}} method. Add child elements, event listeners, etc., to the shadow DOM using regular DOM methods.
  4. If required, define an HTML template using {{htmlelement("template")}} and {{htmlelement("slot")}}. 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.

Tutoriais

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 {{htmlelement("template")}} and {{htmlelement("slot")}} elements, and then use that structure inside your web components.

Referência

Elementos de Custom

{{domxref("CustomElementRegistry")}}
Contains functionality related to custom elements, most notably the {{domxref("CustomElementRegistry.define()")}} method used to register new custom elements so they can then be used in your document.
{{domxref("Window.customElements")}}
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:
Extensions for creating custom built-in elements
CSS pseudo-classes
Pseudo-classes relating specifically to custom elements:

Shadow DOM

{{domxref("ShadowRoot")}}
Represents the root node of a shadow DOM subtree.
{{domxref("DocumentOrShadowRoot")}}
A mixin defining features that are available across document and shadow roots.
{{domxref("Element")}} extensions
Extensions to the Element interface related to shadow DOM:
Relevant {{domxref("Node")}} additions
Additions to the Node interface relevant to shadow DOM:
{{domxref("Event")}} extensions
Extensions to the Event interface related to shadow DOM:

Modelos de HTML

{{htmlelement("template")}}
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 {{domxref("HTMLTemplateElement")}}.
{{htmlelement("slot")}}
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 {{domxref("HTMLSlotElement")}}.
The slot global HTML attribute
Assigns a slot in a shadow DOM shadow tree to an element.
{{domxref("Slotable")}}
A mixin implemented by both {{domxref("Element")}} and {{domxref("Text")}} nodes, defining features that allow them to become the contents of an {{htmlelement("slot")}} element. The mixin defines one attribute, {{domxref("Slotable.assignedSlot")}}, which returns a reference to the slot the node is inserted in.
{{domxref("Element")}} extensions
Extensions to the Element interface related to slots:
CSS pseudo-elements
Pseudo-elements relating specifically to slots:
The {{event("slotchange")}} event
Fired on an {{domxref("HTMLSlotElement")}} instance ({{htmlelement("slot")}} element) when the node(s) contained in that slot change.

Exemplos

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

Especificações

Especificação Estado Comentário
{{SpecName("HTML WHATWG","scripting.html#the-template-element","<template> element")}} {{Spec2("HTML WHATWG")}} The definition of {{HTMLElement("template")}}.
{{SpecName("HTML WHATWG","custom-elements.html#custom-elements","custom elements")}} {{Spec2("HTML WHATWG")}} The definition of HTML Custom Elements.
{{SpecName("DOM WHATWG","#shadow-trees","shadow trees")}} {{Spec2("DOM WHATWG")}} The definition of Shadow DOM.
{{SpecName("HTML Imports", "", "")}} {{Spec2("HTML Imports")}} Initial HTML Imports definition.
{{SpecName("Shadow DOM", "", "")}} {{Spec2("Shadow DOM")}} Initial Shadow DOM definition.

Compatibilidade de navegador

In general:

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

Consulte também