12

I was searching for details regarding the order of execution of functions bound to a page event in javascript, for example via an EventListener.

For example, if I bind three functions A(), B() and C(), to the same event (say DOMContentLoaded), what will be the order of execution of these three functions? One-by-one based on the order of addEventListener call in JS code? Or they are executed all simultaneously?

Besides, can I modify this order? For example, to have a function, bound to DOMContentLoaded event listener, to be executed before any other function bound to the same event.

Carmine Giangregorio
  • 943
  • 2
  • 14
  • 35
  • 1
    Thank you all for the answers; I understand that the order of execution is based on the order of addEventListener call(s). But, how can I be sure that my function will be the first to be called when the page fires the DOMContentLoaded event? I should just place the js script *before* anything else in the page? Does it make differences the fact that the script is in-line or an external file? – Carmine Giangregorio Feb 12 '15 at 15:45
  • Unless your control the page you don’t know if another event listener has been added previously. This question has multiple ways of checking and it seems there is a function that can check but it might only workin the developer console https://stackoverflow.com/a/16544813. Hopefully it will be available outsides if the developer console. – 1.21 gigawatts Oct 29 '21 at 20:14

2 Answers2

17

Event handlers are always called in the order in which they were registered.

Once registered, you cannot insert additional handlers ahead of them[*].


[*] unless you are some how able to obtain a list of all the handlers, and their EventListener objects, and call removeEventListener to remove them, insert your own, and then reinsert the originals. In practise this is likely to be impossible.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 3
    In DOM2, the specification explicitly says that the order in which the handlers attached to an element are called is not guaranteed; but DOM3 changes that, saying that handlers are called in the order in which they're registered. – Ricky Jiao Apr 21 '17 at 08:02
  • 1
    Can you please give a link to the DOM3 specification? Thanks. –  Mar 19 '18 at 06:36
  • @QianChen FYI nothing is listed on MDN in order of execution https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener – 1.21 gigawatts Oct 29 '21 at 10:06
5
var listeners = [];

//add listeners in whatever order you want them executed

document.addEventListener("DOMContentLoaded", function(event) {
    for (var i = 0; i < listeners.length; i++) {
        listeners[i]();
    }
});
thatidiotguy
  • 8,701
  • 13
  • 60
  • 105