Mozilla’s Firefox 63 comes with support for two Web Components: Custom Elements and Shadow DOM. Yesterday, Mozilla shared how these new capabilities and resources are helping web developers to create reusable and modular code.
What are Web Components?
Let’s discuss the two tent pole standards of Web Components v1:
Custom Elements, as the name suggests, allows developers to create “customized” HTML tags. With Custom Elements, web developers can create new HTML tags, improve existing HTML tags, or extend the components created by other developers.
It provides developers a web standards-based way to create reusable components using nothing more than vanilla JS/HTML/CSS. To prevent any future conflicts, all Custom Elements must contain a dash, for example, my-element.
The following are the power Custom Elements provides:
1. Earlier, browsers didn’t allow extending the built-in HTMLElement class or its subclasses. You can now do that with Custom Elements.
2. For the existing tags such as a p tag, the browser is aware to map it with the HTMLParagraphElement class. But what happens in the case of Custom Elements? In addition to extending built-in classes, we now have a Custom Element Registry for declaring this mapping.
It is the controller of custom elements on a web document, allowing you to register a custom element on the page, return information on what custom elements are registered, and so on.
3. Additional lifecycle callbacks such as connectedCallback, disconnectedCallback, and attributeChangeCallback are added for detecting element creation, insertion to the DOM, attribute changes, and more.
Shadow DOM gives you an elegant way to overlay the normal DOM subtree with a special document fragment that contains another subtree of nodes. It introduces a concept of shadow root. A shadow root has standard DOM methods, and can be appended to as any other DOM node but is rendered separately from a document’s main DOM tree.
The underlying concept of Shadow DOM
It is similar to the regular DOM, but differs in two ways:
- How it’s created/used
- How it behaves in relation to the rest of the page
Normally, DOM nodes are created and appended as children of another element. Using shadow DOM, you can create a scoped DOM tree that’s attached to the element, but separate from its actual children. This scoped subtree is called a shadow tree.
The element to which the shadow tree is attached to is called shadow host. Anything that is added in the shadows becomes local to the hosting element, including
Read more in detail about Web Components on Mozilla’s website.