What ? (are these)
Basically async and defer are attributes that can be used by <script> to improve page speed by decreasing loading lag.
Why? (do we use)
We add this attribute to script tag in HTML to control script loading and executing.
How? (it works)
async : This attribute tells browser to download script file asynchronously while continuing to parse the HTML page. Once script has downloaded it executes immediately regardless page parsing.
defer : This attribute also tells browser to download script file asynchronously while continuing to parse the HTML page. Name is self-evidently, it defers execution of script until HTML page has finished parsing.
When? (to use)
async : The script can run before DOM has fully loaded and it doesn’t execute in order. Suitable for scripts which do not perform DOM manipulation.
defer : The script always executes in order in which they appear in HTML. Suitable for scripts which perform DOM manipulation.
Quick Visualization