Reputation: 2290
I read that the module that appears first is loaded first. This wasn't true.
Before I bountied this question I learned:
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:
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?
Upvotes: 15
Views: 2272
Reputation: 31815
The rule is pretty simple: the leafs of the dependency trees are imported first (their code is being executed), then all of the intermediate modules up to the root modules.
That's why you observed this behavior:
1
is a leaf module, it's being executed first (console.log('1')
and the functionExport
declaration)2
imports 1
so it's being executed right after (console.log('2')
)2
eventually calls the function from 1
(console.log('1export'
)The ES6 specification actually doesn't detail clearly whether the imports should be processed sequentially or not. Some browsers might have sequential imports while some other browsers might not.
If you want to guarantee a certain order of execution and have a consistent behavior across browsers, you have to specify a chain of imports accordingly. Two chains of imports are not guaranteed to execute separately (that's why you see DB first sometimes, instead of DC). Two chains of imports are not guaranteed to execute in a certain order (that's why you see sometimes DB, sometimes BD).
The only guaranteed thing is that a script executes after its imports have already executed.
Last word about the async
attribute, it allows to defer the fetching and execution while the browser continues to parse the page. It applies to module
scripts just like regular scripts, the only difference is that they also load their dependencies, to comply with the rule stated above.
Upvotes: 12