While most web-developers will use ReactJS, Angular and simmilar libraries, there
are good reasons to stick with what is already built in the browser.
At my work we use Custom Elements for production ready applications.
One is the frontpage of NRK, where speed is essential, and on NRKs TV many competitions
Web Components are really 3 part, they can be used together or on their own.
The three parts are Custom Elements, Shadow DOM and HTML templates.
Here I will talk mostely about Custom Elements as this is what I have used the most.
Web Components were first introduced in 2011. It has since been in continues
development and is today a living standard (v1).
All modern browsers support Web Components today, for the rest there are pollyfils
and some great libraries.
Custom Elements, much like an React Component, is an reusable element that
can be interactive or just render content in a specific way.
One of the nice things about Custom Element is that you do not need any external libraries
to use it and is a great tool if you have to think about size or speed.
The best way to get a grasp of something is always to read some code.
So let's just get there already
class MyComponent extends HTMLElement {
// Called when element is created (Not added to the DOM)
constructor() {
super();
this.loaded = false;
}
// Called when element is added to the DOM
connectedCallback(){
// Here you can fetch data and call your own render function
this.innerHTML = 'Hello World!';
}
// Called when element is removed from the DOM
disconnectedCallback(){
// Here you should remove any event listeners
}
}
customElements.define('my-component', MyComponent);
And this is pretty much it.
There you have all the building blocks you need to create an interactive website.
You can add your <my-component> element anywhere in your code, directly or dynamically,
the browser will see it and run this code.
There are many libraries that utilise Custom Elements as the base.
My favourite is LitElement by Polymer.