Web Components 101: Hello World

Web Components are a way to encapsulate functionality into little self-contained parts that can be reused and adapted like you’re used to from frontend libraries like React, Vue, Angular or Ember. The special thing about Web components is that they work straight in your browser.

When it comes to support, a lot of features are supported in all major browsers, as can bee checked out at caniuse.com.

As you might have seen, web components usually are understood as several sub-parts, mostly:

HTML Templates (the <template> tag)

Custom Elements (we’ll create one below)

Shadow DOM (the new, cooler iframe that isolates stuff like video players and other comprehensive components a little)

Let’s go ahead and create the easiest possible web component that we can possibly think of, the <hello-world>. Now HTML tags are kind of a free for all kind of buffet, except that you not only can use which ever you want, you can also create which ever you like. So we’ll just name ours what ever the hell we want, while observing the safety restrictions like no numbers or special characters or other shenanigans.

Alright, I know that’s a lot of code to make a “Hello World” appear anywhere. It’s not super useful to us right now, but this shows us a couple of things and is an important stepping stone to the next level!

our shadow variable is our little document within a document and we don’t need a <div id="app"> or similar to render to

the shadow.appendChild makes sure that anything at all gets rendered

customElements.define makes sure that the browser gets the connection between our class HelloWorld and the element tag <hello-world>

Interactive fiddle:

Great! You’ve created your first custom element, if you’ve coded along of course! Now what’s the point, you might ask? Well you can now create rich elements and interfaces without relying on the usual suspects of frameworks or just apply this when you have a task where a framework would be overkill.

Further Reading

If you’ve gotten curious about Web Components and the future of the web that might no longer have any framework wars going on, check out these links: