[JavaScript] The difference between defer and async

Reprinted from: https://segmentfault.com/q/1010000000640869

Let's try a sentence to explain the three, when the browser encounters the script script:

  1. <script src="script.js"></script>
    Without defer or async, the browser will load and execute the specified script immediately. "Immediately" means before rendering the document element under the script tag, that is to say, it does not wait for the subsequent loaded document element, and loads it as soon as it is read. and execute.

  2. <script async src="script.js"></script>
    With async, the process of loading and rendering subsequent document elements will happen in parallel (asynchronous) with the loading and execution of script.js.

  3. <script defer src="myscript.js"></script>
    With defer, the process of loading subsequent document elements will be performed in parallel (asynchronously) with the loading of script.js, but the execution of script.js will be completed after all elements have been parsed and before the DOMContentLoaded event is fired.

And then from a practical point of view, it's best practice to first throw all scripts before, because for old browsers this is the only optimization option, this method ensures that everything else that is not script can be used in the fastest way. Speed ​​gets loaded and parsed.

Next, let's look at a picture: the
write picture description here
blue line represents network reading, the red line represents execution time, both of which are for scripts; the green line represents HTML parsing.

This diagram tells us the following points:

  1. defer and async are the same in network reading (downloading), both are asynchronous (compared to HTML parsing)
  2. The difference between the two is when the script is downloaded and executed. Obviously defer is the closest to our requirements for application script loading and execution.
  3. Regarding defer, the unfinished part of this picture is that it executes scripts in load order, which should be used well
  4. async is a master of out-of-order execution. Anyway, for it, the loading and execution of scripts are next to each other, so no matter the order of your declaration, as long as it is loaded, it will be executed immediately
  5. Come to think of it, async is not very useful for application scripts because it does not consider dependencies at all (even the lowest order execution), but it is for scripts that can or are not dependent on any script. Very suitable, the most typical example: Google Analytics

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324487896&siteId=291194637