Is an inserted element’s connectedCallback guaranteed to run before the callback of a MutationObserver observing it?

25 views Asked by At

Let’s say I’m inserting a custom element <my-element></my-element> into a page and there is a MutationObserver observing the parent element for childList mutations.

In my testing, the connectedCallback of the inserted custom element always fires before the MutationObserver’s callback.

This makes sense, and is what I expect.

What I’d like to know is, is there any way to know that this is guaranteed to always be the case? Is it safe to assume that these callbacks will always fire in this order?

const hostEl = document.getElementById('host');
const templateEl = document.getElementById('async-element');
const asyncElementEl = templateEl.content.cloneNode(true);

const mutationObserver = new MutationObserver((mutationsList, observer) => {
  for (const mutation of mutationsList) {
    const elementsInMutation = Array.from(mutation.addedNodes).filter(
      (node) => node.nodeType === 1
    );
    for (const el of elementsInMutation) {
      console.log(Date.now(), 'observed mutation, inserted:', el);
    }
  }
});

mutationObserver.observe(hostEl, {
  childList: true,
});

if (!customElements.get('my-element')) {
  class MyElement extends HTMLElement {
    constructor() {
      super();
    }

    connectedCallback() {
      console.log(Date.now(), 'connectedCallback', this);
    }
  }

  customElements.define('my-element', MyElement)
}

console.log(Date.now(), 'inserting async element');
templateEl.before(asyncElementEl);
<main id="host">
  <template id="async-element">
    <my-element><div>Hello</div></my-element>
  </template>
</main>

0

There are 0 answers