Difference between constructor and connectedCallback in custom elements v1

As already stated by Juvian in the comments:

  • constructor() is called when the element is created.
  • connectedCallback() is called when (after) the element is attached to the DOM.

The constructor() call is not specific to Custom Elements, it occurs with any object creation (typically created with the new operator), and not only HTML Elements.

In the constructor() call, you can create the Shadow DOM, but you can’t add Nodes inside the normal DOM, and you can’t add or set an attribute either.

About upgrade:

The upgrade occurs when an unknown tag declared in the HTML code is defined afterwards (by the customElements.define() method). The “unknown” element becomes a “custom” element. The constructor() and connectedCallback() methods are then called.

Note: when an element is created (as unknown), and then defined, it is upgraded only when attached.

class CE extends HTMLElement {
  constructor() {
    super()
    console.info( 'constructed' )
  }
  connectedCallback() {
    console.info( 'connected' )
    this.innerHTML = 'Hello'  //can't be set in constructor()
  }
}


B1.onclick = function () {
  ce = document.createElement( 'c-e' )
  ce.textContent="unknown"
}

B2.onclick = function () {
  document.body.appendChild( ce )
}

B3.onclick = function () {
  customElements.define( 'c-e', CE)  
}
<button id=B1>create</button>
<button id=B2>attach</button>
<button id=B3>define</button>

Try different combinations with the above snippet:

  • Run then: 1 Create – 2 Attach – 3 Define
  • Run then: 1 Create – 2 Define – 3 Attach
  • Run then: 1 Define – 2 Create – 3 Attach

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)