HTML:script
lastmod 2018-08-17created 2017-03-112 edits
async vs defer
By default, when a web browser encounters a regular script tag that loads external JavaScript, it pauses parsing the page's HTML code until it has downloaded, interpreted, and executed that script. So if a large script is encountered early in parsing, it even slows down loading of the page, ultimately degrading overall performance, and various tricks have been used to avoid this performance bottleneck. The async and defer attributes of the script tag were introduced to fundamentally prevent this side effect.
Usage is very simple:
<script async src="myAsyncScript.js" onload="myInit()"></script>
<script defer src="myDeferScript.js" onload="myInit()"></script>
Scripts marked async or defer as above are downloaded concurrently without interrupting document parsing, and you can optionally specify an onload handler to perform regular initialization. The key difference between the two is when the script runs: an async script runs as soon as it is downloaded, before the window's load event, whereas a defer script runs after document parsing finishes, before the DOMContentLoaded event, in the order it was inserted into the document.
Html_-script-_async_vs_defer.jpg
The difference in JavaScript execution timing between the two becomes much clearer in the diagram drawn by Peter Beverloo.
Use the defer attribute when the script directly touches and manipulates the document or when loading order among scripts matters; otherwise, use the async attribute to reduce web page loading time.
WebKit-based browsers are said to support both attributes in the future; Firefox already supports both since version 3.6, and Internet Explorer has long supported the defer attribute but does not yet support the async attribute.
In the end, to prevent page loading delays caused by large JavaScript files, tricks are still needed until support for both attributes improves.