are external javascript files loaded sequentially or parallel?

后端 未结 4 1076
我在风中等你
我在风中等你 2020-12-19 04:46

if i have multiple script tags in my page like:

    
    

        
相关标签:
4条回答
  • 2020-12-19 05:26

    Short: Yes:

    Without specifying defer or async properties within the script tag, the spec says, that a browser has to sequentially (sync) load those files.

    In other words, a plain script tag which a browser finds needs to get

    • loaded
    • executed
    • (block any other render/execution process while doing the above)

    While a "modern" browser probably still trys to optimize that process, those steps need to be applied (at least, process-like). That is the reason why you should place script tags without further specification always at the bottom of your <body> tag. Even the DOM render process stops while loading/executing scripts.

    To avoid that, you can specify a defer or async (HTML5 only) property in those script tags, like

    <script defer src="/foo/bar.js"></script>
    

    that tells the browser it is a script that meant to be executed after the document has been parsed.

    See https://developer.mozilla.org/En/HTML/Element/Script

    0 讨论(0)
  • 2020-12-19 05:39

    They are loaded in parallel but they run only once every file have been loaded. So the answer is yes, you can rely on the fact.

    0 讨论(0)
  • 2020-12-19 05:45

    In general, scripts are downloaded sequentially (see this page):

    Because JavaScript code can alter the content and layout of a web page, the browser delays rendering any content that follows a script tag until that script has been downloaded, parsed and executed. However, more importantly for round-trip times, many browsers block the downloading of resources [such as stylesheets, images, and other scripts] referenced in the document after scripts until those scripts are downloaded and executed.

    0 讨论(0)
  • 2020-12-19 05:48

    They may be loaded (via the network) in parallel, but they are evaluated in sequence.

    So yes, you can rely on the order.

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