Typically, the script tag tells the browser to stop parsing HTML, get the script, run it, and only then continue parsing the HTML. This is because the script code can use document.write to output HTML token stream.
async and defer are both mechanisms for telling the browser that everything is in order, and continue to parse the HTML in parallel with downloading the script file and run the script file later, and not immediately.
They are slightly different from each other; this diagram from the script section of the WHAT-WG HTML specification is useful for representing the differences:

Details of the related specifications above, but in brief, for "classic" scripts (the type you're used to, but module scripts will appear soon!):
- Both
async and defer allow parsing of HTML code to continue without waiting for the script to load. defer will cause the browser to wait for the script to execute until the parsing is complete.async will cause the browser to wait for the script to complete loading, which means that it can run the script either before the parsing is complete or after it, depending on when the download is completed (and remember that this may come from the cache).- If
async present and supported by the browser, it takes precedence over defer . async scripts can be executed in any order, regardless of the order in which they appear in HTML.defer scripts will be executed in the order in which they appear in the HTML after the parsing is complete.async and defer well supported even in semi-modern browsers, but are not supported properly in IE9 and earlier, see here and here .
Why do I need the defer flag for a script that manipulates the DOM?
Two reasons:
- This allows you to continue parsing while the script is loading, and
- This means that the script does not run until the parsing completes.
If you did not use defer and you did not place the script tags optimally, using defer helps the script API behave correctly, allowing the browser to complete the construction of the DOM before attempting the script to manipulate it.
Many people still put script tags in the head section of a document, although this is usually the worst place to put them if you don't use defer (or async ). In most cases, the best place (if you have no reason to do something else) is at the very end, before the closing </body> , so A) your site quickly displays without waiting for scripts; and B) the DOM is completely built before trying to manipulate it. A defer recommendation can save their support from people by putting their script tags too early in HTML.
source share