async and defer Script attributes are used to alter when the JavaScript execution happens in HTML page.
When a HTML page is rendered by the browser following happens :
Page is parsed from top to bottom and rendered.
Now if the HTML page contains a script tag following happens:
- HTML page is parsed by the browser.
- Parser encounters script tag.Script tag refers an external JavaScript file.
- Parsing of the HTML is paused.
- The contents of the JavaScript file are fetched from the location referred by the source attribute.
- JavaScript is executed
- HTML parsing is resumed
We can alter this behavior when the script is executed by using the defer and async attributes in the script tag.
defer
When using the defer attribute the JavaScript is fetched from the server but it is executed when the HTML document is completely parsed.
async
- When using the async attribute the JavaScript is fetched from the server along with the HTML parsing.
- Once it has been fetched HTML parsing is stopped
- script is executed
- HTML parsing is resumed
So the main difference between async and defer attributes is that while an async script is executed once it is downloaded ,defer script is executed only after the HTML parsing is complete.There is one other side effect of this behavior:
If there are multiple script tags with async attributes then it is not guaranteed that the scripts will be executed sequentially in order.If one script is downloaded before other scripts then it will executed before other scripts ,irrespective of the order.
Leave a Reply