HTML - HTML Web Components Fundamentals

HTML Web Components are a set of web platform technologies that allow developers to create custom, reusable, and encapsulated HTML elements. Instead of relying on third-party libraries or frameworks, Web Components use built-in browser features to build modular user interface components that work consistently across different web applications. They make code more organized, reusable, and easier to maintain.

Web Components consist of four main technologies: Custom Elements, Shadow DOM, HTML Templates, and JavaScript modules. Together, they provide a standardized way to create components that behave like native HTML elements.

Why Web Components Are Important

Modern websites often contain repeated interface elements such as navigation bars, login forms, buttons, cards, and dialogs. Without Web Components, developers usually copy and paste the same HTML, CSS, and JavaScript across multiple pages. This can make maintenance difficult because updating one component requires editing many files.

Web Components solve this problem by allowing developers to create a single reusable component that can be used anywhere in a project. Once created, it behaves just like built-in HTML tags.

Benefits include:

  • Code reusability

  • Better organization

  • Easier maintenance

  • Encapsulation of styles and functionality

  • Framework independence

  • Improved scalability

Core Technologies of Web Components

1. Custom Elements

Custom Elements allow developers to create their own HTML tags with custom functionality.

For example, instead of repeatedly writing HTML for a user profile card, developers can create a new HTML element.

Example:

<user-profile></user-profile>

This custom tag behaves like any standard HTML element such as <div> or <button>.

To create a custom element, JavaScript is used.

Example:

<script>
class WelcomeMessage extends HTMLElement {

    connectedCallback() {
        this.innerHTML = "<h2>Welcome to our website!</h2>";
    }

}

customElements.define("welcome-message", WelcomeMessage);
</script>

Usage:

<welcome-message></welcome-message>

Output:

Welcome to our website!

Here:

  • HTMLElement is the base class for HTML elements.

  • connectedCallback() runs when the element is inserted into the page.

  • customElements.define() registers the new HTML element.

Naming Rules for Custom Elements

Custom element names must follow certain rules.

Correct:

<student-card>
<product-list>

Incorrect:

<student>

Reason:

A custom element name must contain at least one hyphen (-).

Lifecycle Methods

Custom elements provide lifecycle methods that execute automatically during different stages.

connectedCallback()

Runs when the element is added to the page.

connectedCallback() {
    console.log("Element added");
}

disconnectedCallback()

Runs when the element is removed.

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

adoptedCallback()

Runs when the element moves to another document.

attributeChangedCallback()

Runs whenever a watched attribute changes.

Example:

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

2. Shadow DOM

The Shadow DOM creates a separate DOM tree inside an element. It protects the component's internal HTML and CSS from affecting the rest of the webpage.

Without Shadow DOM:

  • CSS styles may conflict.

  • JavaScript can accidentally modify component content.

With Shadow DOM:

  • Styles remain isolated.

  • Internal structure stays protected.

  • Components become independent.

Example:

class MyCard extends HTMLElement {

    connectedCallback() {

        let shadow = this.attachShadow({mode:"open"});

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

            <h2>Student Card</h2>
        `;

    }

}

customElements.define("my-card", MyCard);

Usage:

<my-card></my-card>

Only the <h2> inside the component becomes blue. Other headings on the webpage remain unchanged.

Shadow DOM Modes

Open Mode

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

The shadow root can be accessed using JavaScript.

Example:

element.shadowRoot

Closed Mode

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

The shadow root cannot be accessed from outside the component.

3. HTML Templates

The <template> element stores HTML that is not displayed immediately. It serves as a blueprint for creating reusable content that can be inserted into the page when needed.

Example:

<template id="card">

<div class="box">
<h2>Student Name</h2>
<p>Computer Science</p>
</div>

</template>

The template remains hidden until JavaScript uses it.

Example:

let template = document.getElementById("card");

let clone = template.content.cloneNode(true);

document.body.appendChild(clone);

Output:

Student Name
Computer Science

The original template remains unchanged and can be reused multiple times.

4. JavaScript Modules

Large applications often contain multiple components. JavaScript modules organize component code into separate files.

Example:

export class StudentCard extends HTMLElement {

    connectedCallback() {
        this.innerHTML = "Student Details";
    }

}

Another file imports it.

import { StudentCard } from "./StudentCard.js";

This improves code organization and maintainability.

Combining All Web Component Technologies

A typical Web Component combines multiple technologies.

Example workflow:

  1. Create a Custom Element.

  2. Attach a Shadow DOM.

  3. Load an HTML Template.

  4. Register the component.

  5. Use the component anywhere on the webpage.

Example:

<student-card></student-card>

<student-card></student-card>

<student-card></student-card>

Each component works independently.

Real-World Applications

Web Components are commonly used to build reusable interface elements such as:

  • Navigation menus

  • Login forms

  • Registration forms

  • Product cards

  • Shopping carts

  • Image galleries

  • Notification boxes

  • Modal windows

  • User profile cards

  • Dashboards

  • Chat widgets

  • Rating systems

Large applications may use hundreds of reusable components.

Advantages of Web Components

  • Creates reusable HTML elements.

  • Reduces duplicate code.

  • Keeps HTML, CSS, and JavaScript together within a component.

  • Prevents style conflicts using the Shadow DOM.

  • Works across modern browsers.

  • Can be used with or without frameworks.

  • Improves scalability for large projects.

  • Simplifies maintenance by centralizing component logic.

  • Supports modular development practices.

  • Enhances collaboration among development teams.

Limitations of Web Components

  • Requires a good understanding of JavaScript.

  • Older browsers may need polyfills for full support.

  • Debugging can be more complex because of Shadow DOM encapsulation.

  • Initial setup takes more effort compared to writing simple HTML.

  • Integration with some older libraries may require additional configuration.

Best Practices

  • Use meaningful names for custom elements.

  • Keep each component focused on a single responsibility.

  • Use Shadow DOM to prevent CSS conflicts.

  • Store reusable markup in HTML templates.

  • Organize components into separate JavaScript module files.

  • Test components in different browsers for compatibility.

  • Ensure components follow accessibility standards by including appropriate semantic HTML and keyboard support.

  • Reuse components wherever possible instead of duplicating code.

Summary

HTML Web Components provide a standardized way to create reusable, self-contained, and maintainable user interface elements using native browser technologies. By combining Custom Elements, Shadow DOM, HTML Templates, and JavaScript Modules, developers can build components that are independent, encapsulated, and easy to reuse across multiple projects. This approach reduces code duplication, improves maintainability, and enables scalable web application development without depending on external frameworks.