A brief introduction to Web Components

Aahlad kethineedi
2 min readMar 11, 2024

--

What are Web Components?

To put it very briefly, A Web Component is a reusable chunk of code which can be reused.

This does not mean that a Web Component has to definitively reusable.

A Web Component can also be designed to cater for a very specific purpose which can only be used once.

To know about Web Components in details, I suggest going through this documentation: Web Components

What is a ShadowDOM?

This a really complex topic. To understand better, I suggest going through this article: ShadowDOM

How to create a Web Component?

A Web Component contains four main lifecycles:

  1. connectedCallback() : triggered when a web component is attached to the shadowDOM.
  2. disconnectedCallback() : triggered when a web component is removed from the shadowDOM.
  3. adoptedCallback() : triggered when a web component is moved to a different document.
  4. attributeChangedCallback() : triggered when a web component’s defined attribute is changed.

Sample Implementation of Web Component:

 class HelloWorld extends HTMLElement {
connectedCallback() {
// Insert HTML content into shadow DOM
this.shadowRoot.innerHTML = `
<style>
/* Add some styling to the component */
.hello-world {
font-size: 24px;
font-weight: bold;
color: green;
}
</style>
<div class="hello-world">
Hello, World! This is a custom HTML web component.
</div>
`;
}
customElements.define('hello-world', HelloWorld);

This can be used in your respective HTML as follows:

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Using HTML Web Component</title>
<script src="hello-world.js" defer></script>
</head>
<body>
<!-- Use the custom element -->
<hello-world></hello-world>
</body>
</html>

That is the basic implementation of Web Components.

--

--

Aahlad kethineedi
Aahlad kethineedi

Written by Aahlad kethineedi

Software Developer. I enjoy reading about Tech and Finance.

No responses yet