Introduction to Web Components API

API Tutorial

In this web development tutorial, we are going to look at web components web developers can leverage to create better maintainability of their codebases, provide high-quality user experiences, and avoid the fate of their web applications becoming obsolete due to outdated technologies or coding principles.

This tutorial assumes that readers are at least aware of web fundamentals such as the basics of programming in HTML, CSS, and JavaScript. However, if you do not have basic knowledge of these technologies, you can still build custom elements, which makes it easy for you to learn about simplifying the complexities of front-end web applications.

Additionally, if you would like to learn web development and HTML in more of a classroom setting, we have a list of some of the Best Online Courses to Learn HTML and Web Development to get you started.

What are Web Components?

In any typical front-end framework, such as Angular, we usually put components that share similar functionalities into a module. However, these components have a drawback – they are dependent on the underlying library or framework, which means if you remove the framework from your project, the components will no longer work. You may be wondering if there is a common component that does not have a dependency on any technology – yes, there are; we have common components that can be used across the range of technologies known as web components. Web components are HTML elements that leverage the power to create new HTML tags and extend existing HTML tags or other components created by another developer.

Since the advent of front-end frameworks, component-based web development has been steadily on the rise. Today, web components are a part of more than 10% of all the pages that load in a browser. Tech giants like Google, Facebook, and Microsoft incorporate web components into their technologies and frameworks. JavaScript frameworks, such as Angular, Next.js, Vue, and React are already making use of web components as well.

You can learn more about the different web development frameworks by reading our tutorial: Best JavaScript Frameworks for Web Developers.

What are the Features of Web Components

Below are some of the features web components bring to the table for web developers and web applications:

  • W3C is continuously working on web component specifications to extend its scope. Programmers will be able to create more common components and since those components do not rely on a framework or library, developers can save time and effort when choosing the right web framework; all programmers need to do is add some HTML, CSS, and JavaScript code to build native web components.
  • Web Components can be used with any JavaScript library or framework that is compliant with HTML. They can be easily created using the browser’s API and do not have a dependency on any third-party library or framework.
  • Web components are non-intrusive. That means they are well organized and have their styling and structure. They do not interfere with any other component or code on the page.

Read: Top Tools for Web Developers

What is the Web Components API?

The power of web components lies in their API. It brings the power to create reusable components with nothing more than HTML, CSS, and vanilla JavaScript. The API uses four web standards as a way of creating reusable components. They are listed below:

  • Custom elements
  • HTML templates
  • ES modules
  • Shadow DOM

Let’s take a more detailed look at each of the web standards that make up the web components API.

Custom Elements

Custom elements are like any HTML elements, such as <p> or <article> tags. Through browser API, we can also create elements ourselves. The custom elements created are just like HTML elements and are enclosed in angular brackets. The name of the custom elements should have a dash in them – for example: <page-header> or <stories-section>.

It should be noted that, to prevent conflict in the future with the names of custom elements, browser vendors have committed to not creating new built-in elements that have dashes within their names.

Custom elements have their own set of semantics, mark-up, and behaviors that you can share across multiple libraries, frameworks, and browsers.

Let’s create a custom element using the following code example:

class ComponentDemonstation extends HTMLElement {
  connectedCallback() {
    this.innerHTML = `<h3>This is a demonstration of Custom elements</h3>`;
  }
}   
customElements.define('component-demo', ComponentDemonstation);

On the HTML page, place the following tag:

<my-component></my-component>

In the example above, we have defined an HTML element known as <component-demo>. As you can see, while defining the custom element, we used the extend keyword. The extend keyword is used to register an element with the browser. Note that all custom elements you create must extend HTMLElement.

Read: Tips to Optimize Website Performance

HTML Templates

HTML5 templates are an excellent way to build reusable layouts using markup. HTML5 templates are a “template” of code that you can put inside an HTML page to render whenever the code is required.

Consider the following code example:

const fragment = document.getElementById('item-template');
const items = [
  { name: 'Bicycle', quantity: 2 },
  { name: 'Dart', quantity: 1 },
  { name: 'Sports Shoes', quantity: 1 }
];

items.forEach(item => {
  // Creating an instance of the template
  const instance = document.importNode(fragment.content, true);
  // Adding relevant content to the template
  instance.querySelector('.name').innerHTML = item.name;
  instance.querySelector('.quantity').innerHTML = item.quantity;
  // Appending the instance of the DOM
  document.getElementById(items).appendChild(instance);
});

In the above code example, we have created a template using <template id=”item-template”>. To consume our newly created template, we can use the following HTML code snippet:

<template id="item-template">
  <li><span class="name"></span> &mdash; <span class="quantity"></span></li>
</template>
<ul id="items"></ul>

    The above code demonstrates how an HTML template can consume a script to tell the browser what to do with it.

    ES Modules API

    Before the ES Modules were introduced, JavaScript did not have any convention to use modules. You can think of a <module> as a collection of features you can reuse in other codebase files. Developers are then required to use <script> tags whenever they want to load JavaScript files into their programs and web applications.

    The ES Modules API introduced the standard way for bundling a collection of features into a library that can be reused in other JavaScript files at some point of time in the future.

    Shadow DOM

    Although the shadow DOM API is not required to create web components, it is a powerful tool for scope customization for individual custom elements.

    As the name implies, a shadow DOM creates a separate DOM tree inside the element it is attached to. In other words, anything inside of the document’s scope is referred to as light DOM and anything inside the shadow root is called shadow DOM.

    Shadow DOM functions like <iframe>, where its content is isolated from the rest of the document. The shadow DOM protects its content from the surrounding variables. It also prevents leakage of CSS and JavaScript code from and into a custom element. Let’s see how you can set-up a shadow DOM. You can attach shadow DOM on any HTML element using the attachShadow() method. Below is a code example illustrating setting up a shadow DOM:

    <div>
      <div id="shadowRootDemo"></div>
      <button id="button">Banana</button>
    </div>

    To attach the shadow root to the above node, use the following script:

    const shadowRoot = document.getElementById('shadowRootDemo').attachShadow({ mode: 'open' });
    shadowRoot.innerHTML = `<style>
    button {
      color: orange;
    }
    </style>
    <button id="button">This will use the CSS color: orange <slot></slot></button>`;

    If you have noticed here, we have used the <slot> element to include the content from the containing document in the shadow root. At the point where you would use the <slot> element, it will drop the user content from the containing document at that designated point.

    Browser Support

    An important thing to consider while working with the web components API is keeping browser compatibility in mind. The Web Component APIs that we have used in this article are fully supported in all modern browsers, such as Firefox, Chrome, and Edge. The exceptions, however, are Internet Explorer 11 and Safari. Microsoft ended support for IE 11 in August 2021, Safari does not support web components, and Apple has no plans yet to support web components in the coming future, so polyfills must be used for these two browsers to fill the browsers’ capabilities gap.

    Final Thoughts on Web Components API

    There is no doubt that web components are going to play a vital role in the development of front-end applications. Web components are already being adopted by large tech companies like Google, Facebook, etc. as their preferred framework and technology. The Accelerated Mobile Pages (AMP) technology and Google’s Polymer framework are examples of the ever-increasing use of web components in the software industry. The Web Components Specification APIs are here to stay longer and continue to grow and evolve as the needs of developers evolve.

    Read: Productivity Tools for .NET Developers

    Tariq Siddiqui
    Tariq Siddiqui
    A graduate in MS Computer Applications and a Web Developer from India with diverse skills across multiple Web development technologies. Enjoys writing about any tech topic, including programming, algorithms and cloud computing. Traveling and playing video games are the hobbies that interest me most.

    More by Author

    Must Read