5

I add several event listeners to input:

['input', 'keydown'].forEach(eventName => {
   document.getElementById('my-input').addEventListener(eventName, e => {
      console.log(`${eventName} event is handled');
   })
})

Also I add mutation observer to document:

const mutationObserver = new MutationObserver(mutationRecords => {
   console.log('Handled mutation records:', mutationRecords);
});

mutationObserver.observe(document, {
    childList: true,
    attributes: true,
    characterData: true,
    subtree: true,
    attributeOldValue: true,
    characterDataOldValue: true
});

If I run this code I see next output:

keydown event is handled

input event is handled

Handled mutation records: ...

As you can see callback of mutation observer was called at the end. And I think that it is expected behaviour, I will explain how I see this:

When I enter symbol in input field all registered event listeners for this input are added to callback queue. After that mutation observer callback is added to callback queue also - as a result we see that mutation observer callback is executed after event listeners callbacks

But If I add event listener to document:

['input', 'keydown'].forEach(eventName => {
   document.addEventListener(eventName, e => {
      console.log(`${eventName} event is handled');
   })
})

I see next output:

keydown event is handled

Handled mutation records: ...

input event is handled

I suppose that it is caused by bubbling of events. Callback of these event listeners aren't added to callback queue at once after symbol was entered, but they are added later after event was bubbled, so we see mixed execution there.

BUT mutation observer is also added to document in example, so something like event bubbling should be applied there, isn't it?

So, my question is:

Is there exact order of execution of event listener callbacks and MutationObserver callbacks? Can I trust to order of execution above, or it may change?

Also please explain if my thoughts are right, and if yes, why in last example output is

keydown event is handled

Handled mutation records: ...

input event is handled

but not:

Handled mutation records: ...

keydown event is handled

input event is handled

Yuriy
  • 1,370
  • 4
  • 14
  • 30
  • 2
    Evidently it's caused by event bubbling but AFAIK the order of execution for tasks (events) and microtasks (the MutationObserver) is not defined in DOM/JS specification so browsers implement it differently and thus you shouldn't rely on the current state as it may change in the future. – wOxxOm May 27 '18 at 17:15

0 Answers0