No history yet

Introduction to Web Components

Building Blocks for the Web

Think about building with LEGO bricks. You have standard pieces like the 2x4 red brick or the 1x2 blue tile. You can combine them in endless ways, but the pieces themselves are consistent and predictable. Web Components bring this same idea to web development.

They are a set of browser technologies that let you create your own custom, reusable, and encapsulated HTML elements. Imagine creating a <user-profile-card> tag that works anywhere, without interfering with the rest of your page's code. Because they're built into the browser, they don't depend on external frameworks.

Three core technologies make this possible:

  • Custom Elements: For defining new HTML tags.
  • Shadow DOM: For encapsulating a component's internal markup and styles.
  • HTML Templates: For creating reusable chunks of HTML.

Create Your Own HTML Tags

The foundation of Web Components is the ability to invent your own HTML elements. Instead of being limited to <div>, <span>, and <p>, you can create tags that are more descriptive of their function, like <special-button> or <color-picker>.

This is done with the Custom Elements API. You define a JavaScript class for your new element's behavior and then tell the browser to associate that class with a specific tag name.

// Define the behavior for our new element
class MyElement extends HTMLElement {
  constructor() {
    super(); // Always call super() first in the constructor
    this.innerHTML = `<h1>Hello from MyElement!</h1>`;
  }
}

// Tell the browser about our new element
customElements.define('my-element', MyElement);

Once defined, you can use <my-element> in your HTML just like any standard tag. The browser will see it and know to run your class logic to create the element's content.

<my-element></my-element>

A key rule for custom elements is that their names must contain a hyphen, like my-element. This helps the browser distinguish them from standard HTML tags.

A Private World with Shadow DOM

One of the biggest challenges in web development is managing CSS. Styles defined for one part of a page can accidentally affect another, causing unexpected visual bugs. This is often called the "global scope" problem of CSS.

Encapsulation

noun

The bundling of data and the methods that operate on that data into a single unit, and restricting direct access to some of an object's components. In Web Components, it means keeping a component's markup, style, and behavior separate from other code on the page.

The Shadow DOM solves this by providing encapsulation. It gives a component its own private, isolated DOM tree. This "shadow tree" is attached to the element but is separate from the main document's DOM. Styles and scripts inside the shadow DOM don't leak out, and styles from the main page don't leak in.

You create and attach a shadow root to an element using JavaScript. From that point on, you can manipulate it just like the regular DOM, but it remains protected from the outside world.

class MyStyledElement extends HTMLElement {
  constructor() {
    super();
    // Create a shadow root
    const shadow = this.attachShadow({ mode: 'open' });

    // Create elements to go inside the shadow DOM
    const wrapper = document.createElement('div');
    wrapper.setAttribute('class', 'wrapper');

    const style = document.createElement('style');
    style.textContent = `
      .wrapper {
        padding: 20px;
        background-color: lightblue;
      }
    `;

    // Attach the created elements to the shadow dom
    shadow.appendChild(style);
    shadow.appendChild(wrapper);
  }
}

Blueprints for Components

Building a component's structure with document.createElement() can get tedious. The HTML <template> element simplifies this. It allows you to declare a chunk of markup that isn't rendered by the browser but can be used later by your script.

Think of a <template> as a stamp. The browser creates the stamp, but it doesn't leave an impression on the page until you decide to use it.

Here's how you can define a template in your HTML and then use it within a custom element. This approach is cleaner and more efficient because the browser only has to parse the HTML once.

<!-- This content is not displayed on the page -->
<template id="card-template">
  <style>
    .card {
      padding: 1rem;
      border: 1px solid #ccc;
      border-radius: 8px;
    }
  </style>
  <div class="card">
    <h2>Card Title</h2>
    <p>Some information about the card.</p>
  </div>
</template>

<script>
  class InfoCard extends HTMLElement {
    constructor() {
      super();
      const template = document.getElementById('card-template');
      const templateContent = template.content;

      this.attachShadow({ mode: 'open' })
        .appendChild(templateContent.cloneNode(true));
    }
  }

  customElements.define('info-card', InfoCard);
</script>

<!-- Now we can use our component -->
<info-card></info-card>

In this example, we combine all three technologies. The <template> holds the structure and isolated styles. The InfoCard class defines the custom element's behavior, which is to clone the template's content and place it inside its own Shadow DOM. The result is a fully self-contained, reusable component.

Quiz Questions 1/5

What is the primary goal of Web Components?

Quiz Questions 2/5

Which technology is responsible for preventing a component's CSS from affecting the rest of the page?

These three technologies—Custom Elements, Shadow DOM, and HTML Templates—form the foundation of Web Components. They provide a standardized, browser-native way to create components that are reusable, maintainable, and framework-agnostic.