Re: [w3c/webcomponents] connectedCallback timing when the document parser creates custom elements (#551)

@franktopel watch out `attributeChangedCallback` might trigger before that and with available children too.

The upgrading mechanism of Custom Elements is easily a footgun for expectations.

If you define the Custom Element before it's found in the body or after, you have already two different behaviors and different possibility to access their content.

In the former case, it'll break until the whole element has been parsed and all its children known too, in the latter case it'll work without problems right away.

Then you have the procedural way to create a custom element with a class ... and that might land on the DOM very late (or even never) so that any recursive interval/animation frame might leak forever if the node gets trashed before it's appended.

Using MutationObserver also might not work because if the custom element is known and it's defined later, no mutation will happen once upgraded.

Example:
```js
customElements.define(
  'my-early-definition',
  class extends HTMLElement {
    constructor() {
      console.log('early', super().children.length);
      new MutationObserver((records, observer) => {
        observer.disconnect(this);
        console.log('early', this.children.length);
      }).observe(this, {childList: true});
    }
  }
);

document.body.innerHTML = `<div>
  <my-early-definition>
    <p>early</p>
  </my-early-definition>
  <my-lazy-definition>
    <p>lazy</p>
  </my-lazy-definition>
</div>`.replace(/\s+/g, '');
```

Copy and paste above code in a bank page. Read _early 0_ and _early 1_.

Now copy and paste the following:
```js
customElements.define(
  'my-lazy-definition',
  class extends HTMLElement {
    constructor() {
      console.log('lazy', super().children.length);
      new MutationObserver((records, observer) => {
        observer.disconnect(this);
        console.log('lazy', this.children.length);
      }).observe(this, {childList: true});
    }
  }
);
```

Read _lazy 1_ and that's it.

Play around putting `connectedCallback` and `attributeChangedCallback` in the mix and see what happens with observed attributes already defined in the element.

Tl;DR **it's complicated**

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/webcomponents/issues/551#issuecomment-429262811

Received on Friday, 12 October 2018 09:23:23 UTC