Javscript async and defer

Hey guys.

I would love some help to understand async and defer JS summary in simpler terms, under script loading strategies https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript#script_loading_strategies.

I feel like I am lost with the technical terms that are being used, to understand the concept.

Thanks again for your help.

Hi @Disney

I’ll try my best. :slightly_smiling_face:

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 :arrow_right: 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

2 Likes

Thank you so much for the help @mikoMK.
I understand the concept well now.
Disney

1 Like