What is Web Components
Web Components are a set of standardised web API that allow you to create reusable, encapsulated and custom HTML elements. It represent a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilise them in your web apps. These components form the cornerstone of modern web application development, enabling developers to build highly interactive, maintainable, and adaptable user interfaces.
At the heart of web components is the concepts of components. A component in a website is a self-contained, reusable piece of the user interface (UI) that can be independently developed, tested, and integrated into different parts of the website. Components encapsulate HTML, CSS, and JavaScript to define a specific functionality or UI element, making it easier to manage and scale large web applications. Imagine you are designing a website for a bakery. This website has several pages, such as the homepage, product pages, and a contact form. Each of these pages includes buttons that perform various actions like “Add to Cart,” “Submit Form,” and “Learn More”. Instead of writing the HTML, CSS, and JavaScript for each button separately on every page, you can create a reusable button component and reuse whenever you might need it in your backery website.
At the heart of Web Components are four main technologies:
- Custom Elements: Custom Elements allow developers to define their own HTML tags
- Shadow DOM: Shadow DOM provides encapsulation for CSS and JavaScript
- HTML Templates : HTML Templates offer the means to declare fragments of markup that are parsed but not rendered
- ES Modules: ES Modules facilitate the modularisation of JavaScript code
This lesson serves as a primer to creating your first Web Component, focusing on the fundamentals of defining and using custom elements in your web applications. Web Components signify a shift towards a more modular and encapsulated way of developing web interfaces, and this session aims to get you acquainted with the process of crafting your own components from scratch.
Creating Your First Custom Element
Web Components revolve around the concept of custom elements, allowing you to define new HTML tags with custom behaviour and appearance. Here’s a step-by-step guide to creating a simple greeting element:
- Create a new HTML file named
index.html
in your project directory.
This is the main HTML file where you’ll use your custom Web Component. It links to the JavaScript file that defines the component, ensuring the custom element’s behavior is loaded and executed. Your index.html might look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web Components Introduction</title>
<script src="my-greeting.js" defer></script>
</head>
<body>
<!-- Custom element used below -->
<my-greeting></my-greeting>
</body>
</html>
In the example above, <my-greeting></my-greeting>
is where your custom element will appear on the web page. The script
tag with the src
attribute pointing to "my-greeting.js"
loads your JavaScript code that defines the my-greeting
element. The defer
attribute is used to ensure that the script is executed after the document has been parsed.
- Create a new JavaScript file named
my-greeting.js
in the same directory.
This JavaScript file contains the definition of your custom element, including its constructor, lifecycle callbacks, and any other logic related to the component. Here’s how the my-greeting.js
file looks based on our example
class MyGreeting extends HTMLElement {
constructor() {
super(); // Always call super() first in the constructor.
// Element functionality written in here.
}
connectedCallback() {
this.innerHTML = `<p>Hello, Ola Nordmann!</p>`; // Set a greeting message
}
}
// Registers the custom element with the browser's Custom Elements registry
customElements.define('my-greeting', MyGreeting);
In the example above, my-greeting.js
defines the behavior of the <my-greeting>
element. When the HTML document loads, it reads this script, registers the custom element, and then you can use <my-greeting>
in the HTML as demonstrated.
Now for any HTML elements with tag
Figure 1. An example of how the HTML file would look after adding the custom element
Understanding the Custom Elements Lifecycle
Custom Elements come with a set of lifecycle methods that allow you to manage the element’s lifecycle effectively:
connectedCallback
: Invoked each time the custom element is appended into a document-connected element.disconnectedCallback
: Invoked each time the custom element is disconnected from the document’s DOM.adoptedCallback
: Invoked each time the custom element is moved to a new document.attributeChangedCallback
: Invoked each time one of the custom element’s attributes is added, removed, or changed.
You can enhance your MyGreeting
element by adding a connectedCallback
to display a greeting message:
class MyGreeting extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.innerHTML = `<p>Hello, Ola Nordmann!</p>`; // Set a greeting message
}
}
Summary
Creating your first Web Component is a significant step towards embracing modern web development practices. By defining custom elements, you’re on your way to building reusable, maintainable, and encapsulated UI components. This session covered the essentials of creating and using custom elements, laying the foundation for more advanced topics in Web Components.
In the following lessons, we’ll explore the Shadow DOM, HTML Templates, and how to manage complex interactions within your custom elements. Stay tuned to deepen your understanding and enhance your web development skills with Web Components.