The script tag is used to load and execute scripts. If the tag is directly used in HTML, the browser will load and execute scripts sequentially and block DOM rendering. Especially when third-party scripts are used, if the server response is slow or the network latency is high, the browser page will display a blank screen for a long time. The async and defer properties of the Script tag can help reduce this problem

Key words: DOM rendering, JS script loading, JS script execution, asynchronous


defer

The script tag sets the defer property, and the browser asynchronously loads the script file without affecting DOM rendering (background loading), executes the script after DOM rendering is complete but before the DOMContentLoaded event is triggered. If there are multiple script tags with this property set, the scripts are executed in the introduced order

try

  • Create an HTML

  • Execute in a browser to see how it loads and executes


As you can see, script 2 (2.01s) is loaded after script 1 (1.00s), but script 2 is executed first, and the DOMContentLoaded event is triggered after the script that defined the defer attribute is executed



The script tag sets the async property, and the browser asynchronously loads the script file in the background and executes the script if it allows. The DOM may not be rendered yet. If there are multiple tags of this type, the script may not be executed in the order introduced. The DOMContentLoaded event took place in uncertain order

try

  • Create an HTML script

  • Browser loading and execution

As you can see, the DOMContentLoaded event fires first and the scripts are not executed in the order they were introduced

Try it again

  • Create an HTML script that takes longer to render

  • Check browser execution

As you can see, this time the DOMContentLoaded event is triggered

As you can see, async does not wait for dom rendering to complete before executing, nor does it execute in the order introduced

Gantt diagram comparison

Regular script

Defer the script

Async scripts



Usage scenarios

  • defer

Use defer in cases where the script relies on the DOM

  • async

Scripts use async without DOM dependency