Frontend with Web Components and Lit-element

Mattia Simonato / Dec 10, 2019

Web components are a collection of web standards allowing you to create new HTML tags with custom names, reusability and full encapsulation on styles & markup. Because they are included in the HTML spec, they are compatible with the big frameworks. None of the big frameworks can avoid supporting HTML (as this is required to render in a browser) therefore support for web components is guaranteed. 

In this blog, we’ll talk about the advantages of using Web Components as well as how to avoid common problems.

Basics

Web Components consist of four main standards which can be used independently or all together:

HTML Templates: necessary for writing reusable code and declaring how it should look

HTML Imports: these let you import HTML code and reuse your components in other pages

Shadow DOM: the rules on how to create a unique DOM encapsulated by HTML markup

Custom elements: needed for adding new HTML elements into the DOM

This DOM addition gives us the ability to “componentize” the web into small, reusable, modular containers that fit into web apps. Best of all, they’re purely built with HTML, CSS, and JAVASCRIPT. 

Challenges 

Some of the most common challenges are:

Code complexity: building web components can be complex and developers often think they will require writing a large amount of code to implement simple functionality.

Shared resource: A web component has its own scoped resources. There may be cases where some of the resources between the components are common.                

Polyfill size: The polyfill are a workaround for a feature that is not currently implemented by the browsers. 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.

Solution

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.

Check out the examples below to see it in action:

HTML

CSS

JS