TIL javascript async vs defer
POSTED ON:
TAGS: javascript performance
The basic tl;dr: (All the sweet ascii graphics were taken from the original source)
Default: #
<script src="/path/to/script.js"></script>
Steps:
- Parse the document.
- Pause document parser
- Download Script
- Execute Script
- Continue parsing
Results:
- The page will remain a white screen until JS is finished.
- The page is not interactable either during that time.
- If the JS is broken, the page can break too. Content can be blocked.
Visual:
┌───────────────────────┬───────────────────────────────────────┬───────────────────┐
/ Parse the document / Pause parsing / Resume parsing /
└───────────────────────┼───────────────────┬───────────────────┴───────────────────┘
/ Download script /
└───────────────────┼───────────────────┐
/ Execute script /
└───────────────────┘
Async: #
<script src="/path/to/script.js" async></script>
Steps:
- Parse the script.
- Download Script during parsing.
- Pause Parsing and Execute Script.
- Continue parsing
Results:
- The page will be interactable. HTML is still available.
┌───────────────────────────────────────────┬───────────────────┬───────────────────┐
/ Parse the document / Pause parsing / Resume parsing /
└───────────────────────┬───────────────────┼───────────────────┴───────────────────┘
/ Download script /
└───────────────────┼───────────────────┐
/ Execute script /
└───────────────────┘
Defer #
<script src="/path/to/script.js" defer></script>
Steps:
- During parsing, download the script.
- Execute the script after the page is ready.
Result:
- Site is interactable, even without JS.
- Content can pop in. If it's below the fold, it won't visually be noticed.
Visual:
┌───────────────────────────────────────────────────────────┐
/ Parse the document /
└───────────────────────┬─────────────────┬─────────────────┘
/ Download script /
└─────────────────┘ ┌───────────────────┐
/ Execute script /
└───────────────────┘
Related TILs
Tagged: javascript