Saturday, 29 August 2020

What really determines the order JavaScript modules are executed in the .html?

I read that the module that appears first is loaded first. This wasn't true.

Before I bountied this question I learned:

  1. Modules that have no imports (leaf modules) are executed first.
  2. A module that imports will not execute until the module it imports from executes.

This has allowed me to explain a basic scenario like this:

2.js logs 2 and exports functionTwo (which, when called, logs "2-export").
1.js logs 1 and imports and executes functionTwo from 2.js.

No matter the source-order of these modules, 2.js always executes first because 1.js can't execute before 2.js - it relies on something 2.js exports to it. The console always reads: '2, 1, 2-export'.


However it is an incomplete answer for these 2 scenarios:

  1. ModuleA imports from ModuleB. ModuleB imports from ModuleA.
  2. ModuleA imports from ModuleB. ModuleC imports from ModuleD. I've been experimenting with source-order and I can't intuitively pick up the rule that determines the complete order of execution of modules. All I do know is that D or B has to execute first. (Sometimes DB or BD executes first; sometimes DC or BA executes first)

P.s.

Is it true that the ruling we're talking about only applies to modules without the async attribute? Is it true modules with the async attribute are simply executed as soon as they are loaded?



from What really determines the order JavaScript modules are executed in the .html?

No comments:

Post a Comment