# JavaScript Loading Strategies in Web Page: async and defer

`<script>` tags are used to download and execute JavaScript on a web page.

Consider these three operations on a web page:

* **HTML Parsing**
    
* **JavaScript Download**
    
* **JavaScript Execution**
    

We can manipulate the sequence of these phases using the following attributes in the `<script>` tag:

* **async** (`<script async src=''></script>`)
    
* **defer** (`<script defer src=''></script>`)
    

### Default Behavior:

By default (`<script src=''></script>`), the script tag **blocks HTML parsing** until the JavaScript is downloaded and executed. This means that the browser will stop parsing the HTML, download the script, execute it, and then resume parsing the HTML.

### `async` and `defer` Behavior:

Both `async` and `defer` **do not block HTML parsing** during the JavaScript download. The script download and HTML parsing happen simultaneously.

* `defer` ensures that the JavaScript is executed **after the HTML parsing is completed**. This means that all deferred scripts are executed in the order they appear in the document, but only after the entire HTML has been parsed.
    
* `async` ensures that the JavaScript is executed **as soon as it is downloaded**, without waiting for the HTML parsing to complete. This can result in the script executing before, during, or after HTML parsing, potentially interrupting it.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1751094129362/bff004c2-856f-484c-bfa9-482cbe0da8b6.png align="center")

Default: JS Download → Execute → HTML Parse

Defer: (HTML Parse + JS Download in Parallel) → JS Execute (after parsing)

Async: HTML Parse + (JS Download → JS Execute when ready, possibly mid-parse)

Use Case

1. Use `async`, when a script has no dependency on others
    
2. Use `defer` when the script depends on other scripts
    

References:

1. [Web dev simplified](https://www.youtube.com/watch?v=BMuFBYw91UQ)
    
2. [Great Front End](https://www.greatfrontend.com/questions/quiz/describe-the-difference-between-script-async-and-script-defer)
