Introduction to Web Components


Introduction
In the evolving landscape of web development, creating modular and maintainable code is paramount. Web Components offer a standardized way to build reusable, encapsulated HTML elements that can be utilized across various web applications. This article provides an overview of Web Components, their core technologies, and practical examples to help integrate them into a project.
What Are Web Components?
Web Components are a set of web platform APIs that allow developers to create custom, reusable, and encapsulated HTML elements. These elements can be used in web pages and applications, promoting code reuse and simplifying complex user interface (UI) development. The primary technologies that constitute Web Components include:
Custom Elements: APIs to define new HTML elements.
Shadow DOM: Encapsulated DOM and styling, ensuring that styles and scripts do not leak into the global scope.
HTML Templates: HTML fragments that are not rendered until they are instantiated via JavaScript.
These technologies work in unison to enable developers to craft components that are self-contained and interoperable with standard HTML elements.
Let's see a custom element in action with this simple example. This info card component demonstrates how to create a basic Web Component that encapsulates its styles and structure. It automatically adapts to light or dark mode based on the user's system preferences, showcasing how Web Components can respect accessibility preferences right out of the box. Try changing your system's theme to see it respond!
Core Technologies of Web Components
1. Custom Elements
Custom Elements allow developers to define their own HTML tags, enhancing the semantics and reusability of web components. There are two types:
Autonomous Custom Elements: Standalone elements not based on existing HTML elements.
Customized Built-in Elements: Elements that extend native HTML elements.
Example of an Autonomous Custom Element:
class MyCustomElement extends HTMLElement {
constructor() {
super();
// Element functionality goes here
}
}
// Define the new element
customElements.define('my-custom-element', MyCustomElement);
In this example, a new custom element <my-custom-element>
is defined, which can be used like any standard HTML tag.
2. Shadow DOM
The Shadow DOM provides a way to encapsulate a component's internal DOM tree and styles, preventing them from affecting the global document. This encapsulation ensures that the component's implementation details are hidden and do not conflict with other parts of the application.
Example of Attaching a Shadow DOM:
class MyShadowElement extends HTMLElement {
constructor() {
super();
// Attach a shadow root to the element
const shadowRoot = this.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = `
<style>
p {
color: blue;
}
</style>
<p>Shadow DOM Content</p>
`;
}
}
customElements.define('my-shadow-element', MyShadowElement);
Here, the <my-shadow-element>
contains a shadow DOM with its own styles and content, isolated from the main document.
The Shadow DOM's style encapsulation is one of its most powerful features, but it can be difficult to understand without seeing it in action. This demonstration shows a side-by-side comparison of global styles versus Shadow DOM styles. Notice how the paragraph in the global document is affected by document-level CSS, while the content in the Shadow DOM remains isolated with its own styling—even though both are paragraphs. This isolation prevents style conflicts and creates truly self-contained components.
3. HTML Templates
HTML Templates define chunks of HTML that are inert and not rendered during page load. They can be instantiated later using JavaScript, allowing for dynamic and efficient DOM manipulation.
Example of Using an HTML Template:
<template id="my-template">
<style>
.template-content {
color: red;
}
</style>
<div class="template-content">Template Content</div>
</template>
<script>
// Access the template
const template = document.getElementById('my-template');
// Clone the content
const clone = document.importNode(template.content, true);
// Append to the document
document.body.appendChild(clone);
</script>
In this example, the content of the <template>
is cloned and inserted into the document, with its styles applied as defined.
The following example demonstrates the power of HTML Templates and Slots for creating flexible, reusable components. This product card gallery uses a template with multiple slots that allow for easy content projection. You can add new products with the 'Add New Product' button to see how components can be dynamically created and populated with custom content. Pay attention to how the template defines the structure while the slots allow for customization
Benefits of Using Web Components
Reusability: Create components that can be easily reused across different projects, reducing duplication and effort.
Encapsulation: Encapsulate styles and behavior, preventing unintended interactions with other parts of the application.
Interoperability: Use custom elements seamlessly with standard HTML, CSS, and JavaScript, as well as with various frameworks and libraries.
Maintainability: Simplify code maintenance by breaking down complex UIs into manageable, self-contained components.
Getting Started with Web Components
To start building Web Components:
Define a Custom Element: Use the
class
syntax to create a new element by extendingHTMLElement
or other built-in elements.Attach a Shadow DOM (Optional): Encapsulate the component's internal structure and styles by attaching a shadow root.
Use HTML Templates (Optional): Define reusable HTML structures that can be instantiated as needed.
Register the Custom Element: Use
customElements.define()
to register the new element with the browser.
Example:
class MyElement extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({ mode: 'open' });
shadow.innerHTML = `
<style>
p {
font-size: 20px;
color: green;
}
</style>
<p>Hello, Web Components!</p>
`;
}
}
customElements.define('my-element', MyElement);
After defining and registering MyElement
, it can be used in HTML as <my-element></my-element>
.
Web Components come alive through their lifecycle callbacks. This interactive example shows a counter component that logs each lifecycle event as it occurs. Try updating attributes, adding or removing the component, and interacting with it to see how and when different callbacks are triggered. This visual demonstration makes abstract concepts like connectedCallback
and attributeChangedCallback
concrete and easy to understand. The real-time log helps you visualize exactly when each part of the component lifecycle is executed.
Real World Applications of Web Components
Web Components aren't just a theoretical concept—they're being actively used by major companies and developers worldwide to solve real-world problems. This section explores practical applications and showcases how these technologies come together to create robust, maintainable solutions.
Bringing everything together, this example shows how Web Components can be composed to create complex, responsive user interfaces. The gallery demonstrates component composition with a parent gallery-grid
component containing multiple gallery-item
children. Try filtering the gallery by category and notice how the components respond to different viewport sizes. This pattern of component composition is the foundation of modern web application architecture, allowing developers to build complex UIs from simple, reusable building blocks.
Conclusion
Web Components provide a powerful set of tools for creating modular, reusable, and encapsulated elements in web development. By leveraging Custom Elements, Shadow DOM, and HTML Templates, developers can build complex user interfaces that are maintainable and interoperable across various platforms and frameworks. Embracing Web Components paves the way for a more component-driven architecture, fostering better code reuse and consistency in web applications.
Subscribe to my newsletter
Read articles from Mikey Nichols directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Mikey Nichols
Mikey Nichols
I am an aspiring web developer on a mission to kick down the door into tech. Join me as I take the essential steps toward this goal and hopefully inspire others to do the same!