Back to all questions

What is the difference between async and defer?

Devs Hive

Devs Hive

Seen on interview: 3 users

This question often comes up in the context of optimizing the frontend of a product. Async and defer are attributes used on the script tag to include external JS files. Both allow the browser to NOT block HTML parsing while scripts are downloading, but they behave differently when it comes to execution. Let's look at how scripts are loaded without any extra attributes and with the async/defer attributes:

No attributes

Downloading external scripts blocks HTML parsing, and everything runs synchronously. If you include several scripts in <head>, the browser will wait until it has downloaded and executed each of them.

<head>
<script src="a.js"></script>
<script src="b.js"></script>
<script src="c.js"></script>
</head>
<body>
<!-- Парсинг HTML буде чекати завершення завантаження і виконання скриптів -->
<h1>Hello</h1>
</body>

Async

With this approach, script downloading does not block HTML parsing and happens in parallel. The script is executed as soon as it has downloaded, even if HTML parsing is NOT finished yet.

<head>
<script src="a.js" async></script>
<script src="b.js" async></script>
<script src="c.js" async></script>
</head>
<body>
<!--
Скрипти виконаються в рандомному порядку,
так як з async порядок виконання не гарантований
-->
<h1>Hello</h1>
</body>

Defer

Like async, defer does not block HTML parsing and downloads in parallel. However, deferred scripts always execute in the order they appear in the document, and only after the DOM has been fully built.

<head>
<script src="a.js" defer></script>
<script src="b.js" defer></script>
<script src="c.js" defer></script>
</head>
<body>
<!-- Виконання буде після DOMContentLoaded, порядок збережений: a → b → c -->
<h1>Hello</h1>
</body>

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!