Web Components in Javascript

Web Components in Javascript

Web Components is a set of web platform APIs that allows you to create custom, reusable, and encapsulated HTML elements. It enables developers to create self-contained components that can be used across different web applications, without worrying about conflicts in styles or behavior.

Web Components Overview

Web Components consist of four main technologies:

  1. Custom Elements: Define new HTML tags and elements.
  2. Shadow DOM: Encapsulate the internal structure and style of a component.
  3. HTML Templates: Define reusable chunks of HTML.
  4. HTML Imports (Deprecated): Allows including HTML documents into other HTML documents (deprecated in favor of ES Modules).

1. Custom Elements

Custom Elements allow you to create new HTML tags, or extend existing ones. These elements are fully customizable and can include their own properties, methods, and events.

Basic Example: Defining a Custom Element

// Define a new class for the custom element class MyCustomElement extends HTMLElement { constructor() { super(); // Always call super() first this.attachShadow({ mode: 'open' }); // Attach shadow DOM for encapsulation } connectedCallback() { // Called when the element is added to the DOM this.shadowRoot.innerHTML = `<p>Hello, this is a custom element!</p>`; } } // Define the custom element customElements.define('my-custom-element', MyCustomElement);

Using the Custom Element

<my-custom-element></my-custom-element>

In the above example:

  • MyCustomElement extends HTMLElement, the base class for all HTML elements.
  • The connectedCallback() method is a lifecycle callback that is called when the element is added to the DOM.
  • The shadowRoot is used to attach a shadow DOM to the element, which helps in encapsulating the internal structure and styles of the element.

2. Shadow DOM

The Shadow DOM is a way to encapsulate styles and DOM structure for custom elements. It allows a component to have its own isolated scope for styles and markup, preventing conflicts with the rest of the page.

Basic Example of Shadow DOM

class ShadowComponent extends HTMLElement { constructor() { super(); // Create a shadow root this.attachShadow({ mode: 'open' }); // Add HTML and CSS to the shadow DOM this.shadowRoot.innerHTML = ` <style> p { color: red; } </style> <p>This is a shadow DOM element!</p> `; } } customElements.define('shadow-component', ShadowComponent);

Key Points:

  • The attachShadow({ mode: 'open' }) method creates a shadow root. The mode can be 'open' or 'closed', where 'open' allows access to the shadow DOM via JavaScript, and 'closed' restricts access.
  • The styles within the shadow DOM only apply to elements inside the shadow root, preventing any style conflicts with the main document.

Using the Shadow Component

<shadow-component></shadow-component>

This will render the content defined in the shadow DOM, and the styles defined in the shadow DOM will not affect the rest of the page.

3. HTML Templates

HTML Templates allow you to define a block of HTML that isn't rendered immediately but can be used later via JavaScript. They are useful for creating reusable and dynamic content.

Basic Example of HTML Template

<template id="my-template"> <style> p { color: green; } </style> <p>This is a template element!</p> </template>

Using the Template with JavaScript

const template = document.getElementById('my-template'); const clone = template.content.cloneNode(true); document.body.appendChild(clone); // This will add the template content to the body

Explanation:

  • The <template> tag defines a block of HTML that won't be rendered when the page loads.
  • The content property contains the content of the template, and it can be cloned using cloneNode(true) to create a copy that can be inserted into the DOM.

4. Shadow DOM with Template

You can combine the Shadow DOM with templates to create more dynamic and reusable components. Here's an example where we create a custom element that uses both a shadow DOM and a template.

Example: Shadow DOM with Template

<template id="card-template"> <style> .card { border: 1px solid #ccc; padding: 16px; border-radius: 8px; } </style> <div class="card"> <h2></h2> <p></p> </div> </template> <script> class CardComponent extends HTMLElement { constructor() { super(); const template = document.getElementById('card-template'); const templateContent = template.content; // Attach shadow DOM to the element this.attachShadow({ mode: 'open' }); // Clone the template content and append it to shadow root this.shadowRoot.appendChild(templateContent.cloneNode(true)); } connectedCallback() { const title = this.getAttribute('title'); const description = this.getAttribute('description'); this.shadowRoot.querySelector('h2').textContent = title; this.shadowRoot.querySelector('p').textContent = description; } } customElements.define('card-component', CardComponent); </script> <!-- Usage --> <card-component title="Web Components" description="Learn about Web Components"></card-component>

In this example:

  • We define a <template> with some structure and styles for a card component.
  • In the CardComponent, we clone the template content and attach it to the shadow DOM.
  • The connectedCallback() method is used to set the title and description of the card from the attributes of the custom element.

Advantages of Web Components

  1. Encapsulation: The use of Shadow DOM allows the internal structure and styles of a component to be completely encapsulated, preventing styles and scripts from leaking into or out of the component.
  2. Reusability: Custom elements are self-contained, making them easy to reuse across different projects or parts of the same project.
  3. Interoperability: Web components work in all modern browsers and can be used in any JavaScript framework, including React, Angular, and Vue.
  4. Cleaner Code: Components are modular, making code more maintainable and easier to understand.

Example: Full Web Component with Shadow DOM and Template

<template id="my-component-template"> <style> div { border: 1px solid #000; padding: 10px; background-color: #f0f0f0; } </style> <div> <h1></h1> <p></p> </div> </template> <script> class MyComponent extends HTMLElement { constructor() { super(); const template = document.getElementById('my-component-template'); const templateContent = template.content; this.attachShadow({ mode: 'open' }); this.shadowRoot.appendChild(templateContent.cloneNode(true)); } connectedCallback() { const title = this.getAttribute('title'); const content = this.getAttribute('content'); this.shadowRoot.querySelector('h1').textContent = title; this.shadowRoot.querySelector('p').textContent = content; } } customElements.define('my-component', MyComponent); </script> <!-- Usage --> <my-component title="My Custom Component" content="This is a description inside a custom web component."></my-component>

Summary of Key Concepts

  • Custom Elements: Define new HTML elements with custom behavior.
  • Shadow DOM: Encapsulate the structure and styles of an element.
  • HTML Templates: Define reusable HTML content that isn't rendered immediately.
  • Web Components: Modular and reusable components that work across frameworks and applications.

With Web Components, you can create powerful and reusable UI elements that can be easily shared and integrated into any web project.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close