Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
  • Overview
  • Transcript

1.2 Use Web Components in Vanilla JavaScript

In this lesson, we’ll first take a look at the template for our web component—this template contains its underlying markup and styling. Next, we’ll use the Shadow DOM to shield this markup from the DOM of the page it’s used on, encapsulating the component’s HTML elements and CSS. Then, we’ll create a custom tag name to aid reuse. Finally, we’ll look at how to import the component into a new page in a separate HTML file.

Code Snippet

To create a web component, we first get the DOM element corresponding to its template.

var template = document.currentScript.ownerDocument.querySelector('template');

Next, we can add a callback that gets invoked whenever the custom element is rendered on a page. Inside the callback, we can create a shadow root for the custom element and import the template.

var progressIndicatorProto = Object.create(HTMLElement.prototype);
progressIndicatorProto.createdCallback = function () {
  var root = this.createShadowRoot();
  root.appendChild(document.importNode(template.content, true));

Finally, we register this callback with the desired element name.

var progressIndicator = document.registerElement ('progress-indicator', {
  prototype: progressIndicatorProto

All we need to do to import the component into another page is use a <link rel="import" href="..."/> element with an href that points to the web component template file.

Related Links

1.Use Web Components in Vanilla JavaScript
2 lessons, 10:51

Free Lesson

Use Web Components in Vanilla JavaScript