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