The async Attribute
Where defer says "run me when the page is ready", async says "run me the moment I arrive." The script downloads in the background without stopping the page, and the instant it has downloaded, the browser runs it, even if it has to pause reading the HTML to do so.
That makes async perfect for scripts that stand alone, and a source of confusing bugs for scripts that do not. This lesson explains both sides. The wider picture is in Script Loading, and its companion is Defer.
What You Will Learnβ
- How an
asyncscript downloads and when it runs - Why it has no guaranteed order
- Which scripts suit
async, and which do not - Why
asyncbugs are flaky, and how to spot them - The
DOMContentLoadedtrap, and how to avoid it - How to call a script's functions before it has arrived
- How to choose between plain,
defer, andasync
The Big Ideaβ
<script src="https://stats.example.com/tracker.js" async></script>
- HTML Code
- Race Lab
<head>
<meta charset="utf-8">
<title>The Bread Bin</title>
<link rel="stylesheet" href="/site.css">
<!-- Your own code: runs after the page is read, in order -->
<script src="/js/lib.js" defer></script>
<script src="/js/app.js" defer></script>
<!-- Independent third-party script: runs whenever it arrives -->
<script src="https://stats.example.com/tracker.js" async></script>
</head>
app.js needs lib.js first. On a calm day, lib.js takes about 200 ms to arrive and app.js about 260 ms.
4 of 20 page loads broke.
This is a simulation with made-up numbers. It only compares which file arrives first, and ignores everything else. It shows why an async bug can hide on your fast connection, then appear for some visitors.
In the lab, begin with async and a small variation. Then raise the variation and load the page again and again. Some loads break, some do not, and that unpredictability is the whole problem. Switch to defer and the bug disappears.
The Rules of asyncβ
- It downloads in parallel, just like
defer. - It runs as soon as it has downloaded. That may be before the page is fully read, or after.
- If it arrives while the page is being read, the parser pauses until the script has run.
- It has no order. Whichever script arrives first runs first, whatever the order in the HTML.
DOMContentLoadeddoes not wait for it. The event can fire before or after an async script runs.- It only works on external scripts. Inline classic scripts ignore it. A module script with
asyncruns as soon as it and its imports are ready, instead of waiting until the end.
async vs deferβ
defer | async | |
|---|---|---|
| Runs | After the page is read | As soon as it arrives |
| Order kept | Yes | No |
| Can pause page reading | No | Yes, if it arrives early |
Does DOMContentLoaded wait for it? | Yes | No |
| Can it use the whole page? | Yes | Not guaranteed |
| Best for | Your own scripts, and scripts that depend on each other | Independent scripts, such as analytics |
A simple rule: if it depends on nothing and nothing depends on it, use async. For everything else, use defer.
The Race Conditionβ
Imagine two scripts, where app.js needs lib.js. On your fast office connection lib.js always arrives first, the page always works, and you ship it. Then a visitor on a different network gets app.js first. It runs, finds no library, and fails.
This is a race condition: the result depends on which download wins. It is the worst kind of bug, because it appears only sometimes, and rarely for the developer. The Race Lab shows it. If you ever see an error like "X is not defined" that comes and goes, check for async on scripts that depend on each other.
The DOMContentLoaded Trapβ
Many scripts start their work like this:
document.addEventListener("DOMContentLoaded", function () {
startApp();
});
That is fine for a plain or deferred script, because the event has not fired yet when they run. But an async script may arrive after the event has already fired. Then the listener waits for something that has already happened, and startApp never runs.
The fix is to check the state first:
function ready(fn) {
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", fn);
} else {
fn();
}
}
ready(function () {
startApp();
});
If the page is still being read, wait. If it is already read, go straight ahead. Code written this way works in every loading mode.
Calling a Script Before It Arrivesβ
Sometimes your page wants to call a function from an async script, but it may not have arrived yet. A common pattern is a small queue: you create a stand-in function that stores the calls, and the real script reads the queue when it arrives.
<script>
window.track = window.track || function () {
(window.track.q = window.track.q || []).push(arguments);
};
track("page_view");
</script>
<script src="https://stats.example.com/tracker.js" async></script>
This only works if the provider's script is built to read the queue, as many analytics tools are. Follow the instructions of the service you use, rather than inventing the pattern yourself.
async Can Still Slow the Pageβ
Async does not block the download, but it can block the parser when it runs. If a big async script arrives while the page is still being read, the page pauses to run it. A heavy third-party tag arriving early can delay your content.
- Keep async scripts small, or load them later (after the page has loaded, or on interaction).
- Remember that running a script still takes time on the main thread, which can hurt responsiveness.
- Check the Performance panel to see whether an async script runs in the middle of page reading.
Scripts Added by JavaScriptβ
A script you add from JavaScript with document.createElement("script") behaves like async by default. If you add several that depend on each other, tell the browser to keep their order:
["/js/lib.js", "/js/app.js"].forEach(function (src) {
const s = document.createElement("script");
s.src = src;
s.async = false;
document.head.appendChild(s);
});
With async = false, scripts added this way download in parallel but run in the order they were added.
Which Mode for Which Script?β
Pick plain, defer, or async for each script, then check your answers.
Checking in DevToolsβ
- Open DevTools, then Network, filter by JS, and reload several times. Does the order of the async scripts change?
- In the Performance panel, record a load, and look for where an async script runs. Does it interrupt the page being read?
- Throttle the network, and reload. Do any "is not defined" errors appear that did not before?
- Use the Console to check for errors from scripts running in the wrong order.
- Try blocking one async script (DevTools can block a request). Does the page still work without it?
Best Practicesβ
- Use
asynconly for independent scripts. - Never use it on scripts that depend on each other. Use
defer. - Write start-up code with a
readyStatecheck, not only aDOMContentLoadedlistener. - Keep async scripts small, or load them late.
- Use a queue where the provider supports one, to call a script before it arrives.
- Make sure the page works if an async script never loads.
- Reserve space for anything an async script adds, so the layout does not jump.
- Test with throttling and repeated loads, to catch race conditions.
Quick Checklistβ
- Every
asyncscript is independent - Dependent scripts use
defer - Start-up code checks
document.readyState - The page works if an async script is blocked or fails
- Async scripts are small, or load after the page
- Space is reserved for anything they add (ads, widgets)
- Several throttled reloads show no "is not defined" errors
Security and Privacy Notesβ
- An async script has the full power of your page, and it runs whenever it arrives, even while the page is half-read. Load scripts only from sources you trust.
- Most async scripts are third-party. Analytics, ads, and widgets can collect data and set cookies as soon as they run. If you need consent first, do not load them until it is given. This is not legal advice, so check the rules that apply to you.
- Use integrity hashes for fixed files. For a script that never changes, add
integrityandcrossorigin="anonymous", so the browser rejects an altered file. - Use a content security policy to limit which hosts may supply scripts. It can also block inline code, so test it carefully.
- Do not make your page depend on an async script for security. For example, do not rely on one to hide or protect content, because it may never load, or may run late.
- Never build a script URL from untrusted input.
Global Audience Notesβ
- A blocked or slow script should not hurt your page. In some regions, networks, or browsers with blockers, third-party scripts never arrive. That is exactly where
asyncis kind: the page carries on without them. Make sure it really does. - Timing differs by network, which is why async bugs show up for some visitors and not others. Test on slow connections as well as your own.
- Heavy tags cost more on modest phones, because running them uses the same limited processor. Keep the number of async third-party scripts small.
- Layout shifts hurt slow networks most. An ad or widget that pops in late and pushes content down is worse when it arrives seconds later. Reserve space for it.
Common Mistakes to Avoidβ
- Using
asyncon scripts that depend on each other. - Relying on a
DOMContentLoadedlistener inside an async script. - Assuming the page is fully read when an async script runs.
- Assuming the order in the HTML is the order of running.
- Loading a heavy third-party tag early, so it pauses the page.
- Using
asyncon an inline script, where it does nothing. - Setting both
asyncanddeferon the same tag. - No reserved space for what an async script adds.
- Testing once on a fast connection, and calling it done.
- Making the page depend on a script that may never load.
Practice Timeβ
- In the Race Lab, set the variation to zero. What happens with
async? Now raise it. What changes? - Click "Load the page 20 more times" several times. Is the number of broken loads the same each time?
- Switch to
defer. How many loads break now? - Take the mode quiz. Which answer surprised you?
- Find a script on a page you built that is independent. Could it be
async? - Rewrite a
DOMContentLoadedstart-up with theready()helper above. - Block one third-party script in DevTools, and see whether your page still works.
- Bonus: find an ad or widget that appears late, and reserve space for it so the page does not jump.
Quick Recapβ
Click a question to check your answer.
1. What does async do?
It downloads the script in the background and runs it as soon as it arrives, pausing the page reading if needed.
2. Why is there no guaranteed order?
Each async script runs when its own download finishes, so whichever arrives first runs first, whatever the order in the HTML.
3. What kind of script is async good for?
Independent scripts that depend on nothing and that nothing depends on, such as analytics or social buttons.
4. Why are async bugs often flaky?
They are race conditions. The result depends on which download wins, which changes with the network. A bug may never show on your own fast connection.
5. What is the DOMContentLoaded trap?
An async script can arrive after that event has already fired, so a listener waiting for it never runs. Check document.readyState first.
6. How do you keep order for scripts added by JavaScript?
Set script.async = false on each one. They then download in parallel but run in the order added.
Key Takeawaysβ
asyncruns as soon as the script arrives, with no order guaranteed.- Use it for independent scripts, and
deferfor everything that depends on something. - Race conditions are flaky. Test with throttling and repeated loads.
- Do not rely on
DOMContentLoadedinside an async script. CheckreadyState. - An async script can still pause the page when it runs, so keep it small or load it late.
- Design for a script that never arrives, and reserve space for what it adds.
- Mind privacy and trust: wait for consent where needed, and use integrity hashes for fixed files.
Next up: Responsive Images and Performance, where you will learn to send each visitor the right image size.