HTML - HTML Web Components

HTML Web Components are a set of modern web platform technologies that allow developers to create reusable, encapsulated, and customizable HTML elements. These components work across different frameworks and libraries such as React, Angular, Vue, or even plain JavaScript. The main purpose of Web Components is to help developers build modular user interface elements that behave like native HTML tags.

For example, instead of repeatedly writing the same navigation bar, card layout, modal window, or custom button, developers can create a single reusable component and use it throughout multiple web pages or applications.

Web Components are based on four major technologies:

  1. Custom Elements

  2. Shadow DOM

  3. HTML Templates

  4. ES Modules

Each of these technologies contributes to creating isolated and reusable components.

1. Custom Elements

Custom Elements allow developers to define their own HTML tags. Normally, HTML provides predefined tags such as <div>, <p>, <button>, and <table>. With Web Components, developers can create entirely new tags such as:

<user-card></user-card>
<custom-button></custom-button>
<image-slider></image-slider>

These custom tags behave like normal HTML elements but contain user-defined functionality.

Creating a Custom Element

A custom element is usually created using JavaScript classes.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>Custom Element Example</title>
</head>
<body>

<hello-message></hello-message>

<script>
class HelloMessage extends HTMLElement {
    constructor() {
        super();
        this.innerHTML = "<h2>Welcome to Web Components</h2>";
    }
}

customElements.define("hello-message", HelloMessage);
</script>

</body>
</html>

Explanation

  • HTMLElement is the base class for all HTML elements.

  • extends HTMLElement allows the new class to inherit HTML behavior.

  • customElements.define() registers the custom tag.

  • <hello-message> becomes a valid HTML element.

When the browser loads the page, the custom element automatically displays the heading.

Naming Rules for Custom Elements

Custom element names must follow certain rules:

  1. They must contain a hyphen (-).

  2. They should not match existing HTML tags.

  3. Names are case-sensitive and generally written in lowercase.

Valid examples:

<app-header>
<user-profile>
<dark-theme-button>

Invalid examples:

<button>
<profile>

The hyphen rule prevents conflicts with future HTML standards.

2. Shadow DOM

The Shadow DOM provides encapsulation for HTML, CSS, and JavaScript inside a component. Encapsulation means the internal styles and structure of a component remain isolated from the rest of the webpage.

Without Shadow DOM, CSS styles from the main page can accidentally affect component styles. Shadow DOM solves this problem.

Example Without Shadow DOM

<style>
h2 {
    color: red;
}
</style>

<h2>Main Heading</h2>

Any <h2> element becomes red.

Example With Shadow DOM

<!DOCTYPE html>
<html>
<body>

<custom-box></custom-box>

<script>
class CustomBox extends HTMLElement {
    constructor() {
        super();

        const shadow = this.attachShadow({ mode: 'open' });

        shadow.innerHTML = `
            <style>
                h2 {
                    color: blue;
                }
            </style>

            <h2>Shadow DOM Heading</h2>
        `;
    }
}

customElements.define('custom-box', CustomBox);
</script>

</body>
</html>

Explanation

  • attachShadow() creates a shadow root.

  • The styles inside the shadow root only apply to the component.

  • External page styles cannot affect internal component styles.

This creates isolated and predictable UI components.

Shadow DOM Modes

There are two modes:

Open Mode

this.attachShadow({ mode: 'open' });

The shadow root can be accessed externally.

Example:

element.shadowRoot

Closed Mode

this.attachShadow({ mode: 'closed' });

The shadow root cannot be directly accessed from outside the component.

3. HTML Templates

Templates allow developers to store reusable HTML content without rendering it immediately on the page.

The <template> element acts as a container for hidden HTML markup.

Example

<template id="cardTemplate">
    <div>
        <h2>User Card</h2>
        <p>This is a reusable template.</p>
    </div>
</template>

The content inside the template is not displayed until JavaScript activates it.

Using Templates

<!DOCTYPE html>
<html>
<body>

<div id="container"></div>

<template id="cardTemplate">
    <div>
        <h2>User Information</h2>
        <p>Reusable template content</p>
    </div>
</template>

<script>
const template = document.getElementById("cardTemplate");
const clone = template.content.cloneNode(true);

document.getElementById("container").appendChild(clone);
</script>

</body>
</html>

Explanation

  • template.content accesses template data.

  • cloneNode(true) creates a copy.

  • The copied content is inserted into the webpage.

Templates improve performance and code reusability.

4. ES Modules

ES Modules allow JavaScript files to be split into reusable modules. Web Components are often organized using modules.

Example

export class MyComponent extends HTMLElement {
    constructor() {
        super();
        this.innerHTML = "<p>Module Component</p>";
    }
}

Another file can import it:

import { MyComponent } from './component.js';

Modules help maintain cleaner project structures.

Lifecycle Methods in Web Components

Web Components provide lifecycle callbacks that run during different stages of the component.

connectedCallback()

Runs when the component is added to the page.

connectedCallback() {
    console.log("Component connected");
}

disconnectedCallback()

Runs when the component is removed.

disconnectedCallback() {
    console.log("Component removed");
}

attributeChangedCallback()

Runs when attributes change.

attributeChangedCallback(name, oldValue, newValue) {
    console.log(name, newValue);
}

observedAttributes

Specifies which attributes should be monitored.

static get observedAttributes() {
    return ['title'];
}

Example of Dynamic Attributes

<user-box title="Administrator"></user-box>

<script>
class UserBox extends HTMLElement {

    static get observedAttributes() {
        return ['title'];
    }

    attributeChangedCallback(name, oldValue, newValue) {
        this.innerHTML = `<h3>${newValue}</h3>`;
    }
}

customElements.define('user-box', UserBox);
</script>

When the title attribute changes, the component updates automatically.

Advantages of Web Components

Reusability

Components can be reused across multiple projects.

Encapsulation

Styles and functionality remain isolated.

Framework Independence

They work with any JavaScript framework or without frameworks.

Maintainability

Large applications become easier to organize.

Cleaner Code

Reusable components reduce repeated HTML and CSS.

Limitations of Web Components

Browser Compatibility

Older browsers may require polyfills.

Complex State Management

Large applications may still need frameworks for advanced state handling.

Learning Curve

Developers must understand multiple technologies together.

Real-World Uses of Web Components

Web Components are widely used for:

  • Navigation bars

  • Modal dialogs

  • Product cards

  • Sliders

  • Tabs

  • Reusable buttons

  • Chat widgets

  • Dashboard panels

Many companies use Web Components to build design systems that work consistently across applications.

Difference Between Web Components and Framework Components

Feature Web Components Framework Components
Standardized Yes Framework-specific
Browser Support Native Requires framework
Reusability High Mostly framework-dependent
Performance Lightweight Can be heavier
Learning Dependency Web standards Framework knowledge

Best Practices

  1. Use meaningful component names.

  2. Keep components small and focused.

  3. Use Shadow DOM for style isolation.

  4. Avoid excessive nesting of components.

  5. Document component behavior clearly.

  6. Use templates for reusable structures.

  7. Test components independently.

Conclusion

HTML Web Components provide a standardized way to create reusable and encapsulated UI elements using native browser technologies. By combining Custom Elements, Shadow DOM, HTML Templates, and ES Modules, developers can build modular web applications without depending heavily on external frameworks. Web Components improve maintainability, consistency, and scalability, making them an important part of modern front-end development.