Reputation: 17057
If I have the following:
<script type="module" src="one.js"></script>
<script type="module" src="two.js"></script>
<script type="module" src="three.js"></script>
three.js
will be executed AFTER one.js
and two.js
?However, if I have:
<script type="module">
import 'one.js'
import 'two.js'
import 'three.js'
</script>
three.js
will be executed AFTER one.js
and two.js
? (this is important)I know it looks like a duplicate question, but please keep in mind that the aim of this question is to confirm the very different behaviour of importing via HTML and via JavaScript
Upvotes: 5
Views: 1000
Reputation: 992
In general, if all modules don't have mutual imports in the both cases are executed modules in the same orders.
In the first case type module
works like defer
script. Code is executed in the correct order after DOM is loaded. It said in the documentation of defer
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer (yellow the box and the next paragraph).
In the second case imports, as you expect, are runs in order that they define in file.
Upvotes: 1
Reputation: 13631
Am I right in saying that you cannot be 100% sure that three.js will be executed AFTER one.js and two.js?
Yes, because for example three.js may have already been imported in one.js, and modules are evaluated only once.
Am I right in saying that I can be confident that three.js will be executed AFTER one.js and two.js? (this is important)
No, for the same reason as above.
In both ways of importing a module, if none of the modules had been imported previously then they would be evaluated in the same order they appear in the markup or code.
In the ECMAScript specification, see the ModuleEvaluation method which iterates through a Source Text Module Record's RequestedModules:
A List of all the ModuleSpecifier strings used by the module represented by this record to request the importation of a module. The List is source code occurrence ordered.
When importing a module using a script tag with the src attribute, if the order of evaluation is not important the async attribute can be used to execute it as soon as it is downloaded.
Upvotes: 2
Reputation: 3166
No, it's not guaranteed to run in same order. It depends on all other files and imports.
Es6 modules are evaluated only once. It means an import statement does not mean an evaluation. When the first host module (module that imports Òne.js
or Two.js
) gets executed, then the imported modules get evaluated. And the same instance will be provided for further imports.
Say A.js
imports Two.js
and gets executed first and B.js
runs afterwards and B.js
imports both One.js
and Two.js
(assuming only these two file import these modules). then in time B.js
gets executed Two.js
already evaluated but One.js
has to be evaluated now.
https://262.ecma-international.org/6.0/#sec-hostresolveimportedmodule
Upvotes: 1