Introducing to Web Components

Introducing to Web Components

[ad_1]

Web components are a set of web platform APIs that allow us to create custom, reusable and encapsulated HTML tags for web pages and web apps. Such custom components and widgets build on the established standards, can work across various browsers, and can be used with any JavaScript library or framework that works with HTML.

Web components specifications

Web components incorporate four (in certain classifications, three) main technologies that can be used together to create versatile custom elements with encapsulated and reusable functionality:

Custom Elements

Custom elements are in essence fully-valid HTML elements, just like <div>, or <article>, but they have custom templates, behaviors and tag names (e.g. <one-dialog>) made with JavaScript APIs. They would always have a hyphen in their name, like <calendar-slider> and browser vendors have committed to create no new built-in elements containing a dash in their names to prevent conflicts. They can be used out-of-the-box with today’s most popular frameworks, including Angular, React, Vue, etc. with minimal effort. Custom elements contain their own semantics, behaviors, markup that can be checked in the HTML Living Standard specification.

Example:

class ComponentExample extends HTMLElement {
    connectedCallback() {
        this.innerHTML = `<h1>Hello world</h1>`;
    }
}
customElements.define(‘component-example’, ComponentExample);

As you can see, custom elements (in this case, <component-example>) must in some way extend an HTMLElement in order to be registered with the browser.

Shadow DOM

The shadow DOM is an encapsulated version of the DOM. It isolates DOM fragments from one another, including anything that could be used as a CSS selector and the corresponding styles, in a somewhat similar to <iframe> manner. At the same time, when we create a shadow root, we still have total control over that part of our page, but scoped to a context. It is critically important as it ensures that a component will work in any environment even if the page has other CSS or JavaScript. More information on how to use encapsulated style and markup in web components can be found in the shadow DOM specification.

Example:

To attach a shadow root, we should run something like:

const shadowRoot = document.getElementById(‘shadow’).attachShadow({ mode: ‘open’ });
shadowRoot.innerHTML = '
    <style>
    button {
        color: purple;
    }
    </style>
    <button id=”button”>Switch to use the CSS color purple <slot></slot></button>';

HTML Template

The HTML <template> element allows us to stamp out reusable templates of code inside a normal HTML flow that is not immediately rendered, but can be used at a later time when called upon. You can write a template of any shape or structure that could be created at a later time. To learn how to declare fragments of markup that go unused at page load, but can be instantiated later on at runtime you can check the HTML template element specification.

Example:

<template id=”movie-template”>
<ul id=”movies”><li>
    <span class=”name”></span> &mdash; 
    <span class=”year”></span> &mdash; 
    <span class=”director”></span>
</li></ul>
</template>

The example above doesn’t render any content until a script has consumes the template, instantiates the code and tells the browser what to do with it.

ES Modules

ES Modules is the recent ECMAScript standard for working with modules. The standardization of a module system for browsers completed with ES6 and browsers started implementing it, so that now ES Modules are supported in Chrome, Safari, Edge and Firefox (since version 60). Modules as collections of smaller components that can be reused in our application, let developers encapsulate all kinds of functionality, and expose this functionality to other JavaScript files, as libraries. The process of including JS documents in a standards based, modular, performant way is defined in the ES Modules specification.

Example:

// From component folder
import { Users } from ‘../components/users.js’;
import { Issues } from ‘../components/issues.js’;
class Dashboard {
    loadDashboard(){
        // Create new instances
        const users = new Users();
        const issues = new Issues();
        console.log(‘Dashboard component is loaded’);
    } 
}
export { Dashboard }

Benefits of web components

Web Components provide multiple benefits for developers and business.

Benefits for code:

  • Reusability: Once created, web components can be imported, used and reused in applications;
  • Readability: Compartmentalized, reusable code reduces the application size, simplified debugging and makes it more readable;
  • Declaration: You can more easily declare components on your page;
  • Composability: Shadow DOM allows composing applications with smaller chunks of code;
  • Extensibility: Custom elements API can extend browser elements or custom web components;
  • Scoping: Shadow DOM ensures DOM and CSS scoping so that styles don’t leak out and component DOM is local;
  • Interoperability: Native web components are interoperable at the browsers lowest (DOM) level.

Benefits for project

  • Brand consistency: Having your front-end application code split up into component libraries or even design systems can ensure brand consistency through the company. It also provides an additional benefit of the ability to be used by all teams, regardless of tech stack;
  • Cost-efficiency: Developers will have the ability to focus solely on making native reusable components, similar to LEGOs, and use these blocks in other applications across teams, which in the end saves money;
  • Faster deployments: Having ready-made code blocks, developers will be able to build and deploy applications more quickly. This leads to less time devoted to developing new features;
  • Quality improvement: As a by-product of reusing and reviewing the same code multiple times, the overall quality will improve in the course of time.

How to use web components?

To use a custom element you can simply import it and use the new tags in an HTML document. The ways to install custom elements, though can vary. Most elements today can be installed with NPM, but it is recommended to look at the README for the commands to install the specific element. NPM also handles installing the components’ dependencies. For more information on NPM, see npmjs.com.

Generally speaking, using a custom element is no different to using a <div> or any other element. Instances can be declared on the page, created dynamically in JavaScript, event listeners can be attached, and so on.

Libraries for building web components

Many libraries already exist that make it easier to build web components, including the following that we find useful:

  • Polymer provides a set of features for creating custom elements.
  • Slim.js provides data-binding and extended capabilities for components, using es6 native class inheritance.
  • Stencil generates standards-compliant web components.
  • Hybrids is a UI library for creating Web Components.
  • Angular provides the createCustomElement() function for converting an Angular component, together with its dependencies, to a custom element.

HTML and DOM specs already add features to support web components, letting web developers easily extend HTML with new elements with encapsulated styling and custom behavior. This proves that web components are already our present and it is time we start using them in applications.

[ad_2]

This article has been published from the source link without modifications to the text. Only the headline has been changed.

Source link