The Anatomy of a Web Component


The web component trifecta

Over the next few lessons, we’ll dive deeper into web components learn about the different browser features that are used to create a web component. These three browser features are:

A stripped back web component example

Here’s all the code for a stripped back component aht renders a copyright sign to the page. There’s going to be a lot of weird and confusing syntax and browser features in the code below. Don’t worry about it! This is just to give you an idea of what a web component looks like.

I’ll break down the code in the next few lessons. By the end, you’ll be able to fully understand what’s going on below:

<body>
	<template id="template">
		<style>
			p {
				font-family: 'DM Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, sans-serif;
				font-size: 1.5rem;
			}
		</style>
		<p>Copyright <span class="year">2024</span>, <span class="name"></span></p>
	</template>

	<odyssey-copyright name="Component Odyssey"></odyssey-copyright>

	<script type="module">
		class OdysseyCopyright extends HTMLElement {
			constructor() {
				super();

				const template = document.getElementById('template');
				const templateContent = template.content;
				const clonedNode = templateContent.cloneNode(true);

				this.attachShadow({ mode: 'open' });
				this.shadowRoot.append(clonedNode);
			}

			connectedCallback() {
				const nameEl = this.shadowRoot.querySelector('.name');
				nameEl.innerText = this.getAttribute('name');
			}
		}

		customElements.define('odyssey-copyright', OdysseyCopyright);
	</script>
</body>

That’s quite a bit of logic for just a couple lines of text. Again, it might look intimidating to begin begin, and it’s completely fine if you have no idea what’s happening. Once we go over the web component fundamentals, it will begin to make more sense. Let’s dive in!