Thursday, February 6, 2014

JavaScript: defer vs async

defer in JavaScript

To run a script block after the page is parsed in other words after the page is loaded, we use the defer keyword in the <script> block.
 

The keyword instructs the browser to wait until ready before executing the JavaScript block.
 

The key rule is the defer attribute will work only for external scripts i.e the keyword can be used only if the JavaScript file is loaded with a src attribute.

syntax:

<script src="test.js" defer>

async in JavaScript

Instructs the browser to run a script block as soon as the the block is available.

There is no wait time here for the browser to be ready. The script block is run in an asynchronous manner as and then the page is being parsed.

syntax:

<script src="test.js" async>

async vs defer

1. aync will take precedence over defer. The script will be asynchronously executed when the page is being parsed.
 
2. If no async but defer, the defer attribute property is executed.
 
3. If not defer or sync, the  script is fetched and executed immediately before parsing.