Sitemap
Marc Kirk

Marc Kirk

…Help me help others — spread the words…

Web Components Introduction

6 min readFeb 18, 2023

--

Press enter or click to view image in full size

Imagine a world where frameworks dont exist. A world where we dont have to learn yet another framework that promises to solve global-famine and dare I say it, cancer!

Whilst the promise of curing cancer is extreme language, it highlights a critical problem with web-development. We have become utterly dependant on frameworks!

For many, frameworks are to development what oxygen is to life. Many developers fear that they cannot build anything useful without a framework. This article will begin to challenge that assertion.

The Problem

Frameworks are the lay of the land, this is what we developers do. We see a shiny framework, spend months or even years learning said framework, build cool stuff with the framework, only for the framework to wilt into obscurity.

So what do we do after a framework wilts? We do what has always been done, we find a shinier framework that promises to rid the world of SHIT code. It is a brutal and unforgiving landscape that demoralises even the hardiest of developers.

So what is the alternative? Enter web-components. A better way to liberate yourself from this dependency hell!

Web Components

Web components are a fantastic way to build modular software. Backed by web-standards and supported by all major browsers — web-components are constantly evolving to meet our complex needs.

This article will walkthrough how to use web-components. We will create a simple <counter-component>that will demonstrate the main features of web-components.

Why Learn Web-Components?

Simple. They help us to create modular and scaleable software that is backed by standards. They promise to be as future-proof as any framework and will replace most frameworks in most situations — eventually…

When frameworks arrive on the scene they are shiny and bright. They lure developers in with grand promises — only to wilt into obscurity. Inevitably, to fill the void, we find shinier frameworks that make even grander promises. Add infinitum. This vicious cycle is false economy and in the long run wastes our time.

What are Web-Components?

Web-components are reusable, modular, custom-elements — built by us! Our custom-elements can be used like regular <html>elements. It is a simple concept but they need several technologies to work.

Technologies that Make Web-Components

Technologies don’t happen in a vacuum and web-components are no exception. To realise the goal of reusable, modular, custom-elements, three technologies are used.

  1. Custom-Element — JavaScript APIs to define custom-elements and their behaviour(s).
  2. Shadow-DOM — JavaScript APIs to attach an encapsulated DOM to a custom-element that is similar to but distinct from the document’s DOM.
  3. HTML-Templates — <template> help to add structure to the custom-elements and are rendered when needed using JavaScript.

Fortunately, these technologies are standardised in the browser, so one less thing to think about.

Creating Custom Elements

Let’s create a <counter-comp> custom-element that demonstrates all the features of a web-component.

Creating and using a custom-element is a three step process.

  1. Create a class to describe your custom-element’s properties and behaviours. Lines 1–7.

2. Register the custom-element and name it with a hyphen. Line 9.

Get Marc Kirk’s stories in your inbox

Join Medium for free to get updates from this writer.

3. Add the custom-element to your html page. See Fig below.

Fig — creating a custom-element named <counter-comp>

You add the <counter-comp> element to your html document, just like a regular html element. See below.

Fig — Add your custom-element to your HTML markup.
Fig— Adding the <counter-comp> element to the HTML markup. Note the $0 which is a reference to the element.

If you query the <counter-comp> element using JavaScript DOM methods, you’ll see that your custom-element behaves like a regular html element. Gotta love web standards!

Press enter or click to view image in full size
Fig — Use your custom-element like a regular html-element. Use DOM methods on your shiny new web-component!

The Web-Component Life Cycle

Inside the custom-element's class, the Counter Class in our case, we define lifecycle callback methods that fire when the custom-element changes. These methods include the:

  1. connectedCallback()
  2. disconnectedCallback()
  3. attributeChangedCallback()

Let’s demonstrate the connectedCallback() and disconnectedCallback()lifecycle methods. When the <counter-comp> custom-element is added to the DOM, the connectedCallback() life cycle method is called, which gets the <counter-comp> class value of hello-world and renders the value inside a <h1> element inside the DOM. Two-seconds later, the <counter-comp> custom-element is removed from the DOM, which triggers the disconnectedCallback() method.

Fig — Dynamically rendering content to the DOM. Note how this refers to <counter-comp>
Figure — connectedCallback() and disconnectedCallback() methods firing

The Counter-Component

Let’s develop the <counter-comp> custom-element. This is a counter with two buttons. One button to increment the counter and one button to decrement the counter. <counter-comp> explores custom-elements, shadow-dom, html-templates and application-state. The basic layout can be seen below. We will improve the look with some CSS later.

Fig — Unstyled <counter-comp> custom-element

Let’s create index.html that contains a custom-element named <counter-comp>. line 4 imports counter.js.

counter.js is the JavaScript class that defines and registers the <counter-comp> custom-element.

Fig — index.html

Now turn your attention to counter.js that defines and registers the <counter-comp> custom-element. I include the life-cycle method connectedCallback() and use a console.log() inside the connectedCallback() method to verify that <counter-comp> successfully connects to the document. Note how ${this} refers to the Counter instance itself. Also, I create a crude render() method that renders basic html when the <counter-comp> custom-element is connected to the DOM.

Shadow-DOM

We want our web-components to work as discrete, independent objects. To realise this goal, we need to encapsulate our web-component.

To encapsulate a web-component into a discrete unit, that operates on its own data, we use the shadow-dom.

The shadow-dom helps to create a web-component with a single responsibility. Having a single responsibility for a software component is one of hallmarks of quality, easily testable software that scales well.

The ultimate goal when we encapsulate web-components is to to keep the html markup, cssstyles and JavaScript methods within a web-component separate from other stuff in the DOM. We do this by attaching a shadow-dom to our web-component. The shadow-dom is distinct from the document’s DOM and acts independently. The shadow-dom effectively isolates our web-component.

Attaching a Shadow-Dom to a Web-Component

Custom-elements and normal-elements can have a shadow-dom-tree attached to them. We then attach other nodes to this shadow-dom-tree to create encapsulated elements.

Let’s attach a shadow-dom to our <counter-comp>custom-element. This shadow-dom starts at that shadow-root. We then attach elements to the shadow-root.

The shadow-root acts just like the normal dom but it is encapsulated from the dom. We can change nodes inside the shadow-root from the DOM itself but the code within the shadow-root cannot effect anything outside the shadow-dom.

Let’s attach a shadow-root to our <counter-comp>custom-element. Line 8. Then we attach htmlelements to the shadow-root. Line 13. Note the attachShadow({mode: 'open'})method. The value of 'open' means that you can access the shadow-DOM with JavaScript from the main-page context. You could access it like so. Conversly, setting the mode to 'closed' means you cannot access <counter-comp>'s shadow-dom from the main-page context. You could say it is closed for modification and enables encapsulation.

const counterCompShadowDom = doucment.querySelector('counter-comp').shadowRoot
Press enter or click to view image in full size
Fig — Accessing <counter-comp>’s shadow-dom
Fig — Attaching a shadow-dom to our <counter-comp>

Recap

We created our own custom-element named <counter-comp> and registered this custom-element so that the browser can attach it to the DOM. We added a connectedCallback() lifecycle method to ease debugging and see what is going on with our custom-element. Finally, we attached a shadow-dom to our custom-element to help facilitate the concept known as encapsulation.

Stay with me for Part 2 of web-components where we dive into passing data to and from custom elements.

Please leave a like and comment. See you in the next article. 😁👍❤️

--

--

Written by Marc Kirk

…Help me help others — spread the words…