Web Component is a feature that is being incorporated in HTML5 DOM Specifications by W3C.
Web Components are a set of APIs’ that allow you to create new custom, reusable, encapsulated HTML tags to use in web apps. Custom Components and widgets build on the web Component standard, will work across modern browsers, and can be used with any JavaScript library or framework that works with HTML.
Web Components are based on existing web standards. Feature to Support web Components are currently being added to the HTML and DOM specs, letting web developers easily extends HTML with new elements with encapsulated styling and custom behaviour.
Web Component building blocks:
1.Custom Elements:
Custom elements API provides developer with the ability to create fully featured standalone DOM elements having their own behaviour and CSS styling. Below is one such example. Where we create an Element showing Movies And its Description
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equip="X-UA-Compatible" content="ie=edge">
- <title>Template Demo</title>
- </head>
- <body>
- Hello World
- <template id="tmpTopMovies">
- <h3> Movie Name </h3>
- <p> Desc </p>
- </template>
- <div id="tmpPlaceholder"></div>
- <script>
- let movies = [
- {name : "Lord of Rings", detail : "Some info about Lord of Rings"},
- {name : "Star Wars", detail : "Some info about Star Wars"},
- ];
- let t = document.querySelector('#tmpTopMovies');
- let pholder = document.querySelector('#tmpPlaceholder');
- for(i in movies)
- {
- t.content.querySelector('h3').innerText = movies[i].name;
- t.content.querySelector('p').innerText = movies[i].detail;
- let clone = document.importNode(t.content,true);
- pholder.appendChild(clone);
- }
- </script>
- </body>
- </html>
In the Above Example there is a template containing Movies Name and Description of the movie. And It is handled by JavaScript. In JS there is an array containing name and details. And adding these array-element to template.
- Shadow DOM.
A shadow tree is a node tree whose root is a shadow root. Shadow DOM provides style and mark-up encapsulation. To create shadow DOM, select an element and call its createShadowRoot method which returns a fragment to which you can append content. This fragment returned is called as Shadow Root. The shadow root and its children are not visible to the user, but browser renders them when it encounters our tag. It allows to isolate DOM of our component and scope and simplify CSS.
- <style>
- /* document style won't apply to the shadow tree inside #elem (1) */
- p { color: red; }
- </style>
- <div id="elem"></div>
- <script>
- elem.attachShadow({mode: 'open'});
- // shadow tree has its own style (2)
- elem.shadowRoot.innerHTML = `
- <style> p { font-weight: bold; } </style>
- <p>Hello, John!</p>
- `;
- //<p> is only visible from queries inside the shadow tree (3)
- alert(document.querySelectorAll('p').length); // 0
- alert(elem.shadowRoot.querySelectorAll('p').length);// 1
- </script>
Description:
Shadow DOM is a way to create a component-local DOM.
shadowRoot = elem.attachShadow({mode: open|closed}) – creates shadow DOM for elem. If mode="open", then it’s accessible as elem.shadowRoot property.
We can populate shadowRoot using innerHTML or other DOM methods.
- HTML Templates:
It defines a new <template> element, which creates chunks of HTML. Templates allow declaration of mark-up fragments which are parsed by the browser as HTML and are not interpreted at page load time but can be used at a later stage. These templates can be instantiated, cloned and reused. Everything inside a <template> tag is considered as inert by the browser.
- <template>
- <p>Hello There.</p>
- <p>I m a template</p>
- </template>
- HTML Imports:
Using HTML templates, you can define templates. But what if the HTML mark-up is quite large, your HTML file will look shabby. Won’t it be good if we can keep our template in a separate file? HTML import is here to our rescue. HTML imports allow to import templates from different HTML files. You can organize your templates in different files and then import them as below: -
- <link rel="import" href="mydocument.html">
Example:
Below is an example of an Image Slider Web Component that changes the image after every 1500ms and updated the image title.
HTML:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equip="X-UA-Compatible" content="ie=edge">
- <title>Template Demo</title>
- </head>
- <body>
- Image Slide
- <template id="image-slider-template">
- <div class="image-container">
- <h4 class="image-title"></h4>
- </div>
- </template>
- <image-slider
- data-images="https://pluralsight.imgix.net/paths/path-icons/nodejs-601628d09d.png,https://camo.githubusercontent.com/eb464a60a4a47f8b600aa71bfbc6aff3fe5c5392/68747470733a2f2f7261772e6769746875622e636f6d2f766f6f646f6f74696b69676f642f6c6f676f2e6a732f6d61737465722f6a732e706e67,https://camo.githubusercontent.com/891e94cd8dda7f40f451bb27067be513c230318a/68747470733a2f2f7261772e6769746875622e636f6d2f766f6f646f6f74696b69676f642f6c6f676f2e6a732f6d61737465722f626f676a732f6a732e706e67" >
- </image-slider>
- </body>
- </html>
JavaScript:
- <script>
- class ImageSlider extends HTMLElement {
- constructor() {
- // If you define a constructor, always call super() first as it is required by the CE spec.
- super();
- }
- connectedCallback() {
- debugger;
- const shadowRoot = this.attachShadow({ mode: "open" });
- const template = document.querySelector("#image-slider-template");
- const instance = template.content.cloneNode(true);
- shadowRoot.appendChild(instance);
- this.images = this.getAttribute("data-images").split(",");
- let imageContainer = this.shadowRoot.querySelector(".image-container");
- imageContainer.style.height = '200px';
- imageContainer.style.width = '200px';
- imageContainer.style.backgroundSize = "contain"
- imageContainer.style.backgroundImage =
- "url(" + this.images[0] + ")";
- this.shadowRoot.querySelector(".image-title").innerHTML = "Image " + 1;
- this.toggleImage();
- }
- toggleImage() {
- let currentImage = 1;
- let images = this.images;
- let shadowRoot = this.shadowRoot;
- setInterval(function() {
- if (currentImage > images.length)
- {
- currentImage = 1;
- }
- debugger;
- shadowRoot.querySelector(".image-container").style.backgroundImage =
- 'url(' + images[currentImage - 1] + ')';
- shadowRoot.querySelector(".image-title").innerHTML =
- "Image " + currentImage;
- currentImage++;
- }, 1500);
- }
- }
- customElements.define("image-slider", ImageSlider);
- </script>
Now that we know which specifications web components leverage, let's look at a custom element's lifecycle. I know, I know, we'll get to the code soon!
A component's lifecycle:
- class MyElement extends HTMLElement {
- constructor() {
- // always call super() first
- super();
- console.log('constructed!');
- }
- connectedCallback() {
- console.log('connected!');
- }
- disconnectedCallback() {
- console.log('disconnected!');
- }
- attributeChangedCallback(name, oldVal, newVal) {
- console.log(`Attribute: ${name} changed!`);
- }
- adoptedCallback() {
- console.log('adopted!');
- }
- }
Following are the methods of a component life cycle:
- constructor():
The constructor runs whenever an element is created, but before the element is attached to the document. We'll use the constructor for setting some initial state, event listeners, and creating the shadow DOM.
- connectedCallback():
The connectedCallback is called when the element is inserted to the DOM. It's a good place to run setup code, like fetching data, or setting default attributes.
- disconnectedCallback() :
The disconnectedCallback is called whenever the element is removed from the DOM. Clean up time! We can use the disconnectedCallback to remove any event listeners or cancel intervals.
- attributeChangedCallback(name, oldValue, newValue) :
The attributeChangedCallback is called any time your element's observed attributes change. We can observe an element's attributes by implementing a static observedAttributes getter.
- adoptedCallback():
The adoptedCallback is called each time the custom element is moved to a new document. You'll only run into this use case when you have <iframe> elements in your page.
Top comments (0)