docs.rodeo

MDN Web Docs mirror

Web Components

{{DefaultAPISidebar("Web Components")}} 

Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.

Concepts and usage

As developers, we all know that reusing code as much as possible is a good idea. This has traditionally not been so easy for custom markup structures — think of the complex HTML (and associated style and script) you’ve sometimes had to write to render custom UI controls, and how using them multiple times can turn your page into a mess if you are not careful.

Web Components aims to solve such problems — it consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions.

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

  1. Create a class in which you specify your web component functionality, using the class syntax.
  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.

Guides

Reference

Custom elements

Shadow DOM

HTML templates

Examples

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

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

In this article

View on MDN