HTML5 gave us async and defer to better control the browser page rendering flow.
By default when the browser sees a <script>
tag’s src link, it will pause the HTML parsing, download the script, execute it, and only then resume the HTML parsing.
Putting your <script>
tags at the bottom of your HTML is a good practice, but async
and defer
provide us with more control.
Here is how to use them and what are their differences:
Using async:
<script async src="/js/zepto.min.js"></script>
async
will ensure the HTML parsing is ONLY stopped for the script execution.
The script will be downloaded while parsing the HTML.
The script execution happends right it has been downloaded, pausing the HTML parsing.
Using defer:
<script defer src="/js/zepto.min.js"></script>
defer
is like async
, EXCEPT that the script execution will be done AFTER the HTML parsing is done.
HTML parsing is NEVER paused with defer.
When to use which? See this small article »