Let's try one sentence to explain the three, when the browser touches script the script:
-
<script src="script.js"></script>
No defer or async , the browser will immediately load and execute the specified script, "immediately" means before the document element under the tag is rendered, that is script , not waiting for subsequent loading of the document element, read to load and execute.
-
<script async src="script.js"></script>
There async , the process of loading and rendering subsequent document elements will be script.js loaded and executed in parallel (asynchronously).
-
<script defer src="myscript.js"></script>
There defer , the process of loading subsequent document elements is done script.js in parallel with the load (async), but script.js the execution is DOMContentLoaded done before the event fires after all element parsing is complete.
And then, from a practical point of view, it is best practice to first throw all the scripts </body> before, because this is the only optimization option for the old browser, which guarantees that all other elements of non-scripting can be loaded and parsed as quickly as possible.
Then, let's take a look at the picture:
The Blue line represents the network read, the red line represents the execution time, both are for scripting, and the Green Line represents HTML parsing.
This diagram tells us the following points:
- defer and async in the network read (download) This piece is the same, is asynchronous (compared to HTML parsing)
- The difference between the two is that when the script finishes downloading, it's clear that defer is closest to our request for application script loading and execution.
- With regard to defer, the picture is that the script is executed in the order of loading, which is a good use of
- Async is a random execution of the main, anyway, for it to load and execute the script is next to each other, so no matter what the order of your declaration, as long as it is loaded, it will be executed immediately
- To think about it,async is not very useful for application scripting because it does not consider dependencies at all (even the lowest order), but it is a good fit for those scripts that can be independent of any script or that are not dependent on any script, the most typical example: Google Analytics
HTML <script> element Async,defer asynchronous loading