Sling Academy
Home/JavaScript/Create Framework-Agnostic UI Using Web Components in JavaScript

Create Framework-Agnostic UI Using Web Components in JavaScript

Last updated: December 13, 2024

In modern web development, creating reusable and framework-agnostic components is essential for building scalable and maintainable applications. Web Components provide a standardized way to create encapsulated and interoperable custom elements using native browser capabilities without relying on any specific JavaScript framework. In this article, we'll explore how to create Web Components in JavaScript step by step with practical examples.

Understanding Web Components

Web Components consist of four main specifications:

  • Custom Elements: Allow developers to define new HTML tags.
  • Shadow DOM: Provides encapsulation for the component's internal DOM structure and styling.
  • HTML Templates: Define reusable markup structures.
  • HTML Imports: (Deprecated) Used for including HTML files in other documents. Modern alternatives include JavaScript imports and JavaScript modules.

Creating Custom Elements

Custom Elements are at the heart of Web Components. Let's create a simple custom element to understand how they work.

// Define a class for the new element
class MyCustomElement extends HTMLElement {
  constructor() {
    super();
    console.log('Custom element constructed');
  }

  connectedCallback() {
    this.innerHTML = "<p>Hello, I am a web component!</p>";
  }
}

// Register the custom element
customElements.define('my-custom-element', MyCustomElement);

The above script defines a new custom element named my-custom-element. When added to an HTML document, it outputs a paragraph with text.

Using Shadow DOM for Encapsulation

Encapsulation is one of the defining features of Web Components, ensuring that the styles and scripts do not interfere with the rest of the application. This can be achieved using the Shadow DOM.

class ShadowComponent extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'open' });
    const paragraph = document.createElement('p');
    paragraph.textContent = 'This is inside the shadow DOM.';
    const style = document.createElement('style');
    style.textContent = `
      p {
        color: blue;
        font-size: 20px;
      }
    `;
    shadow.appendChild(style);
    shadow.appendChild(paragraph);
  }
}

customElements.define('shadow-component', ShadowComponent);

In the above example, the Shadow DOM is used to contain its styles and markup, preventing it from bleeding into the global scope.

Leveraging HTML Templates

HTML Templates are more efficient for repetitive DOM management. They can be defined in HTML and then cloned and appended to the Shadow DOM when needed.

<template id="my-template">
  <style>
    div {
      color: red;
    }
  </style>
  <div>This is a template content!</div>
</template>
class TemplateComponent extends HTMLElement {
  constructor() {
    super();
    const shadow = this.attachShadow({ mode: 'open' });
    const template = document.getElementById('my-template').content.cloneNode(true);
    shadow.appendChild(template);
  }
}

customElements.define('template-component', TemplateComponent);

This example demonstrates how to use the HTML Template to encapsulate a style along with the HTML content.

Integration and Usage

Integrating these components into your web pages is as simple as including their tag in the HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Web Components Demo</title>
  <script src="/path/to/your/components.js" defer></script>
</head>
<body>
  <my-custom-element></my-custom-element>
  <shadow-component></shadow-component>
  <template-component></template-component>
</body>
</html>

Overall, Web Components offer a powerful and flexible way to create reusable, maintainable, and framework-agnostic UI elements that can be utilized in a variety of web projects. They integrate seamlessly in native HTML, ensuring smooth interoperability with any libraries or frameworks that might be in use. Happy coding!

Next Article: Enhance Modularity and Maintainability with JavaScript Web Components

Previous Article: Reuse UI Blocks Across Projects via JavaScript Web Components

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration