The cart is empty

Web Components are a set of technologies that enable developers to create reusable custom elements – with their own functionalities, independently of the library or framework being used. This modularity leads to better code organization, easier maintenance, and development of web applications. The fundamental pillars of web components include Custom Elements, Shadow DOM, HTML templates, and ES Modules.

Custom Elements

Custom Elements allow developers to define custom HTML tags. These elements can have their own JavaScript logic and CSS styles, making them fully functional components that can be used in HTML just like standard elements. To create a custom element, you first need to define a class in JavaScript that extends HTMLElement, and then register this class using the customElements.define() method.

Example:

class MyComponent extends HTMLElement {
  constructor() {
    super();
    // component initialization
  }
}

customElements.define('my-component', MyComponent);

 

Shadow DOM

Shadow DOM enables encapsulation of your component's JavaScript and CSS, preventing conflicts with styles and scripts on the main page. This means you can have styles defined inside the component that won't affect or be affected by styles outside the component.

Example:

class MyComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'open'}).innerHTML = `<style>p { color: red; }</style><p>Hello, world!</p>`;
  }
}

customElements.define('my-component', MyComponent);

HTML Templates

HTML Templates are templates that can be defined in HTML using the <template> element. These templates can contain any HTML code, which remains "inactive" until activated with JavaScript. This is particularly useful for defining the structure and content of components to be dynamically inserted into the DOM.

Example:

<template id="myTemplate">
  <p>Hello, world!</p>
</template>
const template = document.getElementById('myTemplate').content;
document.body.appendChild(template.cloneNode(true));

ES Modules

ES Modules (EcmaScript Modules) are a standard for modular code in JavaScript, allowing importing and exporting parts of code between different files. This approach is ideal for organizing the code of web components because it enables easy sharing of functions, classes, and more between components.

Example:

// file: component.js
export class MyComponent extends HTMLElement {
  // component class definition
}

// in another file
import { MyComponent } from './component.js';
customElements.define('my-component', MyComponent);

Web Components offer developers a powerful tool for creating reusable, isolated, and modular parts of web applications. With technologies like Custom Elements, Shadow DOM, HTML templates, and ES Modules, it's possible to build complex user interfaces that are easily maintainable and extensible.