Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I apply template in constructor or connectedCallback

Tags:

When should I apply template in constructor or connectedCallback ? When I do it in callback sometimes attributeChangedCallback is called before and i can't query for elements.

export class TestElement extends HTMLElement {
  constructor() {
    super();
    //here ?
  }

  connectedCallback() {
    //here ?
  }
}

I would like to know where and why it is better.

Here is a snipped of template apply code

let t = document.createElement('template');
t.innerHTML = require('template.html');
this.appendChild(t.content.cloneNode(true));
like image 564
vardius Avatar asked May 12 '17 06:05

vardius


1 Answers

If you don't use Shadow DOM you should not insert template in the constructor() callback.

Therefore you should append it only in connectedCallback().

Anyways attributeChangedCallback() can be called before or after the above callbacks depending on how your custom element is used. So you should always make a test before trying to query some inner elements.

like image 139
Supersharp Avatar answered Sep 24 '22 09:09

Supersharp