async and defer script
<script>
tag is used to include javascript files in a webpage.
Plain <script>
For normal <script>
tags without any async
and defer
, when they are encountered, HTML parsing is blocked, the script is fetched and executed immediately. HTML parsing resumes after the script is executed.
<script async>
In <script async>
, the script will be fetched in parallel to HTML parsing, after finishing download, browser stops HTML parsing before executing downloaded code (potentially before HTML parsing finished completes yet) and it will not necessarily be executed in the order in which it appears in the HTML document. Use async
when the script is independent of any other scripts on the page, for example, analytics.
<script defer>
In <script defer>
, the script will be fetched in parallel to HTML parsing and executed when the document has been fully parsed, but before firing DOMContentLoaded
. If there are multiple of them, each deferred script is executed in the order they appeared in the HTML document.
If a script relies on a fully-parsed DOM, the defer
attribute will be useful in ensuring that the HTML is fully parsed before executing.
Notes
- Generally, the
async
attribute should be used for scripts that are not critical to the initial rendering of the page and do not depend on each other, while thedefer
attribute should be used for scripts that depend on / is depended on by another script. - The
async
anddefer
attributes are ignored for scripts that have nosrc
attribute.<script>
withdefer
orasync
that containdocument.write()
will be ignored with a message like "A call to document.write() from an asynchrnously-loaded external script was ignored".