Understanding the CustomElementRegistry Object

Gil Fink
2 min readJul 3, 2018

--

Custom Elements

I was asked couple of times during sessions about Web Components API what can we do with the CustomElementRegistry object. This post will shortly explain what is the object and where it is helpful except for registering your elements.

If you register them, they will come

The CustomElementRegistry object main functionality is… to register your new and shiny custom elements. The object is accessible through the window.customElements object. In order to register a custom element you will use the define function. The define function receives the name of the custom element, the element’s constructor function (or class definition) and an options object. Once registered, the element is defined and can be created in declarative way (in your HTML) or using the document.createElement function. The following code example shows the usage of the define function with a NotificationElement class (which is of course a custom element definition):

window.customElements.define('notification-element', NotificationElement);

Defined/Not Defined

What is going to happen if the custom element isn’t defined yet but we added it to our HTML? In those situations you will probably want to use some placeholder instead of the element or maybe delay the usage of the element’s functionality. This is where the CustomElementRegistry’s whenDefined function comes handy. The whenDefined function receives a name of a custom element and returns a promise. The promise will be resolved when the custom element is defined. This behavior enables us to know exactly when an element is defined and to act accordingly. The following code will check if a notification-element is defined, and only when it is it will call it’s show function:

let elm = document.querySelector('notification-element');
window
.customElements.whenDefined('notification-element').then(()=>{
elm.show('hello');
});

Trying to use the show function before the element is defined will probably raise an error.

Getting an Element Constructor

The last CustomElementRegistry function, which is currently as I write only experimental, is the get function. The get function receives an element name and returns it’s constructor. The function is useful if you want to use the constructor function somewhere in your code to instantiate an element manually without the document.createElement function.

Summary

In the post I shortly introduced the CustomElementRegistry object and it’s current exposed API. I hope that you found the content helpful. If you have any other questions, feel free to ask in the comments :)

--

--

Gil Fink
Gil Fink

Written by Gil Fink

Hardcore web developer, @sparXys CEO, Google Web Technologies GDE, Pro SPA Development co-author, husband, dad and a geek.

No responses yet