An initializer, commonly called a constructor, runs when a class is instantiated. In a Web Component, it runs when the element is created, before the element is added to the DOM. section 2.1 section 4.2
When defining a custom element, keep these timing rules in view:
- Call super() first when extending HTMLElement; this invokes the inherited constructor. section 4.2
- Create an element with document.createElement() to trigger its constructor without adding it to the page. section 4.2
- Use connectedCallback when work depends on the page DOM; ordinary innerHTML and related element DOM APIs are not yet available during construction. section 4.0 section 8.2
- With Shadow DOM, attach a shadow root in the constructor and initialize its contents immediately. section 8.2
A custom element initializer
class MyCustomTag extends HTMLElement { constructor() { super(); this.serviceURL = 'http://company.com/service.json'; this.counter = 0; this.error; } connectedCallback() { this.innerHTML = '<h2>' + this.getAttribute('title') + '</h2>'; } } The constructor establishes component state. The connectedCallback performs page-DOM work after insertion. Writing innerHTML directly in the constructor fails for a custom element, but writing to shadowRoot after attachShadow() is supported. section 4.2 section 8.2
Listing 9.14. Slider component constructor
constructor() { #1
super();
this.attachShadow({mode: 'open'}); #2
this.shadowRoot.innerHTML =
Template.render(); #3
this.dom = Template.mapDOM(this.shadowRoot);
document.addEventListener('mousemove', e => this.eventHandler(e));
document.addEventListener('mouseup', e => this.eventHandler(e));
this.addEventListener('mousedown', e => this.eventHandler(e));
}
Trace a complete constructor-based component: call super(), attach an open shadow root, render a template, map its DOM, and register event handlers. section 9.5








