You are currently viewing html5 web components

html5 web components

HTML5 Web Components are a set of web platform APIs that enable developers to create reusable, encapsulated, and self-contained components for use in web applications. More specifically, they allow the creation of custom HTML elements that function independently, with scoped styles and behavior, thus eliminating conflicts with other elements on the page.

Importance of Web Components in Modern Web Development
Over the years, Web Components have revolutionized front-end development by promoting modularity, code reusability, and consistency. Moreover, They are framework-agnostic, meaning they can be used with any JavaScript library or framework, ensuring long-term compatibility and reducing development overhead. 

To start your career in software development, enroll in our full web development full course and become a software developer in 8 months!

Core Concepts of HTML5 Web Components

1. Shadow DOM

The Shadow DOM technique allows developers to encapsulate a component’s internal structure and styling in a separate, isolated “box.” 

In simple terms, this shadow tree is attached to an element in the light DOM (the main page content), but its structure and styles remain separate. One of the main advantages of Shadow DOM is encapsulation, which prevents the styles and behaviours inside the shadow tree from leaking out to the main DOM and vice versa.

How It Works
When a Web Component is created, a shadow root is attached to an element using the JavaScript method attachShadow(). This shadow root is a hidden, encapsulated DOM that affects only the component’s internal rendering, not the whole document. 

Developers can apply styles and structure to this shadow tree without worrying about conflicts with other parts of the page.

For example, if a custom component includes its styles, those styles will only affect elements inside the shadow tree, leaving the other document’s styles untouched. This encapsulation provides a clear boundary, which leads to cleaner and more maintainable code.

Use Case:
For instance, a custom button component with its styles and behavior can be defined using Shadow DOM. Its CSS (e.g., button colors, padding) won’t conflict with other styles on the page, and it won’t accidentally inherit unwanted styles from the global document.

Key Points:

  • Isolation: Styles and scripts in the Shadow DOM do not affect the rest of the document.
  • Scoping: Styles and behavior are scoped to the component, reducing the risk of side effects.
  • Encapsulation: Component logic is isolated, which leads to better reusability.

2. Custom Elements

Custom Elements are essentially new, user-defined HTML tags. They enable developers to extend HTML by creating new elements with custom behaviour and appearance. 

These elements can be as simple as a button or as complex as a carousel. Custom Elements allow for the creation of reusable, encapsulated UI components that work just like standard HTML elements.

How They Work:
To create a Custom Element, you extend the HTMLElement class in JavaScript and then define it using custom elements.define(). The syntax for defining a custom element requires specifying:

  1. The name of the custom tag.
  2. The class that defines the behaviour of the element.

Here’s a basic example of creating a custom element:

class MyButton extends HTMLElement {

  constructor() {

    super();

    this.attachShadow({mode: 'open'}); // Attach shadow DOM

    this.shadowRoot.innerHTML = `<button>Click me</button>`;

  }

}

customElements.define('my-button', MyButton); // Define the custom element

This example creates a custom button element (<my-button></my-button>) that behaves like a regular HTML element but is encapsulated with its styles and structure inside a shadow DOM.

Use Case:
In particular, Custom Elements are used when you need to define a reusable UI component (e.g., custom form fields, alert boxes) that can be easily imported and reused across different projects or frameworks.

Key Points:

  • Reusability: Once defined, Custom Elements can be used like native HTML elements anywhere in your codebase.
  • Extensibility: Developers can extend standard HTML elements or create entirely new ones with unique behaviours.
  • Integration: Custom Elements can be used within existing HTML documents or within frameworks like React, Angular, or Vue.

3. HTML Templates

The <template> tag is a way to define HTML fragments that are not rendered when the page loads. Instead, they are stored in the browser’s memory until they are explicitly activated (cloned and inserted) by JavaScript.

 As a result, the template content is inert and not part of the DOM until it’s used, which makes it highly efficient for defining reusable sections of HTML code.

How It Works:
The content inside a <template> tag is parsed by the browser but not rendered until JavaScript accesses it.

 A typical use case would be to define a structure (such as a list item or a modal) that can be duplicated whenever necessary. Subsequently, JavaScript can clone the template’s content and insert it into the DOM dynamically.

Example:

<template id="myTemplate">

  <div class="modal">

    <p>Welcome to my modal!</p>

  </div>

</template>
<script>

  const template = document.getElementById('myTemplate');

  const clone = document.importNode(template.content, true);

  document.body.appendChild(clone);

</script>

Use Case:
HTML templates help create components that must be repeated multiple times, such as list items in a dynamic list, without duplicating HTML manually.

Key Points:

  • First and foremost, Performance: Since templates are not part of the DOM until they’re activated, they save resources.
  • Furthermore, Reusability: Templates allow you to define reusable chunks of HTML that can be inserted into the page as needed.
  • Additionally, Dynamic Content: JavaScript can modify and populate the template before appending it to the DOM.

How to Create a Custom HTML5 Web Component: Step-by-Step Guide

Creating a custom HTML5 Web Component involves a few essential steps: defining a template, creating a class to extend HTMLElement, attaching Shadow DOM, and registering the custom element. 

Below is a detailed step-by-step guide to help you create a functional and reusable web component.

  1. Define a Template Using <template>

A template is a portion of HTML that isn’t rendered until it’s explicitly used by JavaScript. The <template> tag holds the structure of your custom element, which will be cloned and inserted into the DOM dynamically.

Example:

<template id="myButtonTemplate">

  <style>

    button {

      background-color: #4CAF50;

      color: white;

      padding: 15px 32px;

      text-align: center;

      font-size: 16px;

      border: none;

      cursor: pointer;

    }

    button:hover {

      background-color: #45a049;

    }

  </style>

  <button>Click me</button>

</template>

In this example, the template defines the structure of a simple button and some styles for it. The id=”myButtonTemplate” attribute helps us reference this template later.

2. Create a Class Extending HTMLElement

In this step, we create a JavaScript class that extends the HTMLElement class. This class will define the behavior and structure of the custom element. Inside the class, we define a constructor method that will initialize our component.

Example:

class MyButton extends HTMLElement {

  constructor() {

    super(); // Always call super() first to get the element's context

    // Attach a Shadow DOM to this element to encapsulate styles and structure

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

    // Get the template content and clone it

    const template = document.getElementById('myButtonTemplate');

    const templateContent = template.content.cloneNode(true);

    // Attach the cloned content to the Shadow DOM

    this.shadowRoot.appendChild(templateContent);

  }

}

In the MyButton class:

  • We call super() to initialize the HTMLElement base class.
  • The attachShadow({ mode: ‘open’ }) method attaches a Shadow DOM to the custom element, ensuring that the styles and structure inside it remain isolated.
  • We access the template content by referring to the template’s ID, cloning it, and appending it to the Shadow DOM using this.shadowRoot.appendChild().

3. Attach Shadow DOM for Styling and Structure

The Shadow DOM provides encapsulation, so any styles defined within the component won’t affect other parts of the page. This helps ensure that the component’s design remains consistent.

We already added the Shadow DOM in the previous step with this.attachShadow({ mode: ‘open’ }). When the template is cloned, the styles inside it are scoped to the component, meaning they only apply to the contents of the component’s shadow tree.

4. Register the Custom Element with customElements.define()

Finally, to make the custom element available for use, we register it with the customElements.define() method. This method takes two arguments:

  1. The name of the custom element (must include a hyphen, e.g., my-button).
  2. The class that defines its behavior.

Example:

customElements.define('my-button', MyButton);

Now, the custom element <my-button></my-button> can be used anywhere in your HTML.

Complete Example

Here’s the full code for creating and using the custom HTML5 Web Component:

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Custom Button Component</title>

</head>

<body>

  <!-- Use the custom element -->

  <my-button></my-button>

  <template id="myButtonTemplate">

    <style>

      button {

        background-color: #4CAF50;

        color: white;

        padding: 15px 32px;

        text-align: center;

        font-size: 16px;

        border: none;

        cursor: pointer;

      }

      button:hover {

        background-color: #45a049;

      }

    </style>

    <button>Click me</button>

  </template>

  <script>

    class MyButton extends HTMLElement {

      constructor() {

        super(); // Initialize the element

        this.attachShadow({ mode: 'open' }); // Create Shadow DOM

        // Access the template and clone its content

        const template = document.getElementById('myButtonTemplate');

        const templateContent = template.content.cloneNode(true);

        // Append cloned content to Shadow DOM

        this.shadowRoot.appendChild(templateContent);

      }

    }

    // Register the custom element

    customElements.define('my-button', MyButton);

  </script>

</body>

</html>

Key Concepts and Keywords:

  • Custom Elements: User-defined HTML elements that extend HTMLElement.
  • Shadow DOM: An isolated DOM that encapsulates the structure and styles of a component.
  • Template: A reusable HTML structure that is inactive until referenced and cloned by JavaScript.

Encapsulation: Ensuring that the component’s styles and functionality don’t interfere with the rest of the document.

Leave a Reply