Search code examples
firefox-addonpageload

Influencing the order of page load handlers in Firefox extensions


For some Firefox extensions it makes sense to get their hands on page content as early as possible for modification, whereas for others as late as possible (e.g. when other extensions may be done with their modifications). It's clear that there will always be extensions that want to be "first" or "last", but I'm having a hard time finding material covering this online. For addEventListener("load", ...) I can only find that the order in which event handlers get called is undefined. If there's no way for addEventListener, then what other options to influence early/lateness of handling content do I have in Firefox extensions?


Solution

  • The order in which event listeners are triggered is indeed undefined, you cannot rely on any particular order. As far as extensions go, your best bet is to write code in such a way that you don't care whether other extensions are already done or not. Other than that, you can choose which event to attach:

    • chrome-document-global-created/content-document-global-created notifications run at the earliest possible point in time, when the window was just created - but the window's contents won't be available yet. This option obviously isn't something that you can use if your code is loaded by an overlay of the window, loading overlays happens way later.
    • DOMContentLoaded event happens once the window's DOM can be accessed.
    • load event happens later, once all dependent elements load.
    • If you want to run even later, there is the option of calling setTimeout(..., 0) in a load event handler - the timeout is guaranteed to execute after all the load event handlers.