Hi @Disney
I’ll try my best.
I find the image in this chapter helpful:
For the colors:
- parser (green): Creating the page from the HTML tags.
- fetch (blue): Download the JS file.
- execution (red): Run the JS code.
In the image we see that both async
and defer
download the script in parallel to the HTML parsing (non-blocking). The difference is the time when the code runs.
-
async
runs as soon as possible and blocks the HTML parsing.
-
defer
runs after the the HTML parsing is finished.
Another important difference is that when we have multiple async
scripts we don’t know which runs first. This means we should only use async
when the scripts don’t depend on each other. (script2 is after script1 in the HTML code and script2 needs script1, but script2 runs first ERROR)
defer
scripts always run in the same order as they appear in the HTML file.
I hope that makes it a bit clear. Feel free to ask more questions, if needed.
Michael