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

前端 未结 1 1817
深忆病人
深忆病人 2021-02-14 06:07

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 m
相关标签:
1条回答
  • 2021-02-14 06:52

    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.

    0 讨论(0)
提交回复
热议问题