Web Components
A Comprehensive study on web components why to use, when to use, when not to use, performance, limitations, challenges with use cases and examples
A web component is a standardised way of creating encapsulated, reusable user interface elements for the web.
Introduction
- Web Component is similar to that of components in frameworks such as React, Angular or Vue.
- It is a reusable UI building block that encapsulates all the HTML, CSS and any JavaScript-based logic required to render it.
- The big difference is that instead of relying on a specific JavaScript framework it leverages technologies natively provided by the browser so that your Web Components are framework agnostic.
- The technologies that Web Components leverage from the browser are features such as Custom Elements, Shadow DOM, ES Modules and HTML Templates.
- The Custom Element API allows you to define new HTML tags with associated templates, styling and logic. The styling can be encapsulated using the Shadow DOM which makes your component ignore any styles applied outside of it.
At the end of this article, you can find the GitHub link and npm lib link to test web components
Features
- Define new HTML/DOM elements
- Create elements that extend from other elements
- Logically bundle together custom functionality into a single tag
- Extend the API of existing DOM elements
Pros and Use Cases
- Adaptability
Building a reusable component library using Web Components allows you to adapt to the ever-evolving JavaScript frameworks landscape.
- Consistency(Decouple)
Web Components can be a great solution for companies that use different JavaScript frameworks across different sites and would like to keep the look and feel of those sites consistent
- Design Pattern
Web Components are a particularly good option for organizations that use different tech stacks across different teams or projects. Instead of developing multiple render targets for your Design System, you can build a component library that can be consumed across all the different tech stacks.
- Progressive Web Apps
Progressive Web Apps (PWAs) are web applications that are regular web pages or websites but can appear to the user like traditional applications or native mobile applications. The application type attempts to combine features offered by most modern browsers with the benefits of a mobile experience.
Using Web Components you can create Progressive web apps (Many google apps are built using Web Components)
- Future foresight (Ease to switch framework)
Web Components can also be good for future changes in your site.
For example, say that your site currently uses React and you have built all your components in React. Then in the future, either due to business decisions, technology advances or maintainability issues, your company decides to switch to a different JavaScript framework. In that case, your company would have to develop new components in this new framework. Alternatively, if your company’s component library was built using Web Components, that library can be re-used in the new JavaScript framework thus saving costs and time.
Will it work in any browser?
Yes, with the appropriate polyfills. Evergreen browsers such as Chrome, Firefox and Safari support most features natively. Edge is currently in the process of building native support for Web Components.
However, there is a bit of a caveat in Safari: custom elements extending HTMLElement will work but not custom elements extending built-in elements such as HTMLButtonElement, but the good news is customized built-in elements will work in Safari with an appropriate polyfill like document-register-element.
Challenges?
- Styling and updating the Shadow DOM:
Styling the shadow dom isn’t possible, You can’t update styling or penetrate into the components. We can’t use dom API and query selector to manipulate or alter.
(Solution: You can use slots in some cases to solve the above problem)
- Performance:
Increase in the number of web components takes more time to get used inside the DOM.
(Still, it doesn’t impact much generally)
- Polyfill size:
The polyfills are a workaround for a feature that is not currently implemented by the browsers for browser support. These polyfill files have a large memory footprint.
- SEO:
As the HTML markup present inside the template is inert, it creates problems in the search engine for the indexing of web pages.
Though there are solutions or way around are already available for these challenges
Limitation
- Server-side rendering web components :
Biggest Limitation that I found in web components
Rendering web components on the server is not possible because there is no way to declaratively represent shadow roots and their content in HTML — or to attach them to a host — without executing imperative JavaScript on the client
(Though there are few workarounds)
2. Importing web components in SSR in SPA :
While trying to import web component in nextjs i found you can’t directly import
Your web component, we need to import our web component in componentDiDMount Method. As it’s a SSR . It will raise an issue when you’ll try to compile.
(You’ll feel what’s the issue in this approach, check the next point).
3. SEO:
SEO and other boats which reads your page source won’t be able to crawl underlying html inside a web component
Which directly impacts SEO as web crawler won’t be able to read the html source
Core technologies of Web Components
- Custom Elements
- Shadow DOM
- HTML Imports
- HTML Templates
- Custom Elements
With Custom Elements, web developers can create new HTML tags, beef-up existing HTML tags, or extend the components other developers have authored. The API is the foundation of web components. It brings a web standards-based way to create reusable components using nothing more than vanilla JS/HTML/CSS. The result is less code, modular code, and more reuse in our apps.
- Shadow DOM
Shadow DOM removes the brittleness of building web apps. The brittleness comes from the global nature of HTML, CSS, and JS. Over the years we’ve invented an exorbitant number of tools to circumvent the issues. For example, when you use a new HTML id/class, there’s no telling if it will conflict with an existing name used by the page. Subtle bugs creep up, CSS specificity becomes a huge issue (!important all the things!), style selectors grow out of control, and performance can suffer. The list goes on.
Shadow DOM fixes CSS and DOM. It introduces scoped styles to the web platform. Without tools or naming conventions, you can bundle CSS with markup, hide implementation details, and author self-contained components in vanilla JavaScript.
- HTML Imports
HTML Imports is intended to be the packaging mechanism for web components, but you can also use HTML Imports by itself.
You import an HTML file by using a <link> tag in an HTML document like this:
You can load any resource including scripts, stylesheets, and web fonts, into the imported HTML just like you do to regular HTML files:
doctype, html, head, body aren’t required. HTML Imports will immediately load the imported document, resolve subresources and execute JavaScript, if any.
<link rel=”import” href=”myfile.html”>
- HTML Templates
HTML Templates — Specialized DOM elements <template> and <slot>that allow you to create reusable base markup for a custom element with pieces that are overridable on a per-instance basis. (Note that these elements aren’t rendered, so you can define them anywhere in your document.)
Libraries
A comprehensive comparison of performance and size of all the libraries
- Stencil
A library which carries advantages of react and angular. Better project Structure and Ease of maintaining and developing. By far i found stencil very easy to use and develop web components in Stencil
Advantage
- Bundle size:
The idea of providing polyfills only when needed and relaying on native web technologies makes Stencil.js very attractive, as the boilerplate around each component is reduced to a minimum and the amount of kb sent each time is very small. Moreover, you just don’t care about polyfilling non compliant browsers — Stencil.js does it for you. - Virtual DOM
- Async rendering (inspired by React Fiber)
- Reactive data-binding
- TypeScript
- JSX
- Static Site Generation (SSG)
2. Lit Element
Lit-element is a simple base class for creating fast, lightweight web components. Its familiar development model makes it easier than ever to build Web Components. You can express your UI declaratively, as a function of state.
No need to learn a custom templating language — you can use the full power of JavaScript in your templates. Elements update automatically when their properties change.
LitElement also uses lit-html to define and render HTML templates. DOM updates are lightning-fast because lit- html only re-renders the dynamic parts of your UI — no diffing required.
GIT Repository :- https://github.com/rishisahu94/webcomponents
Branches:
For Stencil implementation: stencil-webcomponent
For Stencil with nexjs(ssr) implementation: stencil-with-nextjs
For Lit Element and Vanilla js implementation :lit-element-and-vanilla-js
NPMJS
Library : https://www.npmjs.com/~rishisahu20
References:
https://medium.com/@treshugart/%C3%A5server-side-rendering-web-components-e5df705f3f48
https://developers.google.com/web/fundamentals/web-components
https://www.webcomponents.org/community/articles
https://medium.com/rangle-io/everything-you-need-to-know-about-web-components-part-1-ced95964fbe6
https://www.grapecity.com/blogs/web-components-introduction-creating-custom-html-elements-2018