Why Should I Learn About Web Components?
--
Web Components, an eclipsed standard by modern Web Frameworks.
This article aims to be a starting point in the universe of web components. It provides some basic concepts necessary to understand why they are important.
What is a Web Component?
Let’s start with the definition from MDN definition:
Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps.
To understand web components is essential to know some concepts, so let’s deep dive into it.
Custom Elements
Custom elements are a way to create your HTML tags defined by the WHATWG as:
Custom elements provide a way for authors to build their own fully-featured DOM elements
So, HTML allows us to develop, distribute and use an element like this one:
Shadow DOM
The impact of Shadow DOM in the development of web components is really important, so let’s try to understand them. MDN definition:
Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree starts with a shadow root, underneath which can be attached to any elements you want, in the same way as the normal DOM.
As part of the definition, I’ve highlighted in bold this sentence: “hidden DOM trees to be attached to elements in the regular DOM tree??”
What does this means, and why is it so important??
The key concept here is encapsulation, or the ability to add new content to your website that does not interfere with the previous one.
- Styling (CSS): we can distribute a custom element with its CSS, and the CSS of the website will not modify ours. We could still do it using CSS Custom Properties/CSS Variables.
- Events (JS): Events that happen in shadow DOM have the host element as the target when caught outside of the component.
Learn more about Shadow DOM modes: open vs. close
What About the Usage?
Nowadays, the support for web components is broadly extended:
And here is the support for CSS Variables:
As you can see, most modern browsers support both standards.
Conclusions
I hope that this small introduction to web components helps you understand better what they are.
I encourage you to click the different links and learn more about these exciting concepts.