Custom Element Lifecycle

Permalink to "Custom Element Lifecycle"

Custom elements come with a set of lifecycle hooks. In this section you'll use two of them:

The constructor is called when the element is first created: for example, by calling document.createElement(‘rating-element') or new RatingElement(). The constructor is a good place to set up your element.

It's bad practice to do DOM manipulation in the constructor.

This is because DOM manipulations can slow down initial load times, and cause some problems in some edge cases.

The connectedCallback is called when the custom element is attached to the DOM. This is typically where initial DOM manipulations happen.

Render DOM

Permalink to "Render DOM"

Now, return to the custom element and associate some DOM with it. Set the element's content when it gets attached to the DOM:

In the constructor, you store an instance property called rating on the element. In the connectedCallback, you add DOM children to <rating-element> to display the current rating, together with thumbs up and thumbs down buttons.

This example is not following accessibility best practices for controls and inputs.