Introduction
Did you ever came across a situation when you created a really nice UI component for an application and wanted to use it in another application but both application were using an entirly different framework due to which it was difficult for you to port the component from one application to the other.
Web components are set of web APIs that allows you to create custom, reusable components for web applications. These custom components add in the HTML vacabulary and can be used in any Javascript library or framework. So they let developers easily extend HTML with new elements.
Magic behind the elements
So how are we as developers are enable to create new custom elements and use them anywhere we want. If you run your developer console and run following
window.customElements
You will find a bunch of properties and mathods. I am sure you have a clue about how you can extend your browser's html vacabulary.
Defining a new HTML element
Custom elements are nothing but simple Javascript classes that extend base HTMLElement class. Following are the steps to create a new simple custom element
- Create Javascript element by creating a new class that extends HTMLElement.
class MyCustomComponent extends HTMLElement { ... }
- Add the newly created element in the list of custom components
window.customElements.define ('my-custom-element', MyCustomElement);
- That's it, you can now add the component in any application by using following tag
<my-custom-element></my-custom-element>
Comments
Post a Comment