If neither attribute is present, the script is downloaded and executed synchronously, and will halt parsing of the document until it has finished executing (default behavior). Scripts are downloaded and executed in the order they are encountered.
defer attribute downloads the script while the document is still parsing but waits until the document has finished parsing before executing it, equivalent to executing inside a
DOMContentLoaded event listener.
defer scripts will execute in order.
async attribute downloads the script during parsing the document but will pause the parser to execute the script before it has fully finished parsing.
async scripts will not necessarily execute in order.
Note: both attributes must only be used if the script has a
srcattribute (i.e. not an inline script).
<script src="script.js"></script> <script src="script.js" defer></script> <script src="script.js" async></script>
- Placing a
deferscript in the
<head>allows the browser to download the script while the page is still parsing, and is therefore a better option than placing the script before the end of the body.
- If the scripts rely on each other, use
- If the script is independent, use
deferif the DOM must be ready and the contents are not placed within a