The defer Attribute
defer is the closest thing HTML has to a free speed-up. Add one word to a script tag, and the browser stops waiting for that script. It downloads the file in the background while it carries on reading the page, and runs it later, when the page is ready.
The idea is simple, but the details trip people up: exactly when does a deferred script run, in what order, and what breaks when you add it to an old page? This lesson answers those questions. For a quick overview, see the Script lesson, and for the wider picture, Script Loading.
What You Will Learnβ
- Exactly when a deferred script downloads, and when it runs
- Why deferred scripts keep their order
- What
deferdoes not work on - The four bugs that appear when you add
deferto an old page - How
deferrelates toDOMContentLoaded - How to convert an old page safely
- What
deferdoes and does not make faster
The Big Ideaβ
<script src="/js/app.js" defer></script>
Compare that with a plain script tag. The plain one stops the parser, downloads, runs, and only then lets the page continue. The deferred one downloads at the same time as the page is being read, and waits its turn.
- HTML Code
- Run Order Lab
<head>
<meta charset="utf-8">
<title>The Bread Bin</title>
<link rel="stylesheet" href="/site.css">
<!-- Found early, downloaded in the background, run in this order after the page is read -->
<script src="/js/lib.js" defer></script>
<script src="/js/app.js" defer></script>
</head>
<body>
<h1>The Bread Bin</h1>
<p>This content can appear before either script has run.</p>
</body>
<script src="/js/lib.js"></script>
<script>Lib.start();</script>
<script src="/js/app.js"></script>
<h1>The Bread Bin</h1>
What happens, in order
- lib.js downloads, then runs (the parser waited). It defines Lib.
- The inline script uses Lib, and it works.
- app.js downloads, then runs (the parser waited).
- app.js uses Lib, and it works.
- The parser reaches the heading, so the page can start to appear.
- HTML is fully read. document.readyState is now interactive.
- DOMContentLoaded fires.
Scripts that held up the heading: 2. Errors: 0.
This is a simplified model of the usual order of events. It leaves out styles and timing, so confirm real behaviour in your browser.
In the lab, start with everything plain and read the errors. Then add defer one script at a time. Watch how the order of events changes, and how the inline script breaks when lib.js is deferred. The checkbox at the bottom shows the usual fix.
The Rules of deferβ
- It downloads in parallel. The browser finds the script as it reads the head, and starts the download at once, without stopping.
- It runs after the HTML is fully read. The page is already built, so your script can use any element on it.
- It runs before
DOMContentLoaded. That event waits until deferred scripts have finished. - It keeps its order. Deferred scripts run in the order they appear in the HTML, even if a later one downloads first. If an earlier script is slow, later ones wait for it.
- It runs once, on the main thread. Deferring moves the waiting out of the way, but the script still has to run, and while it runs the page cannot respond.
What defer Works Onβ
| Script | Does defer apply? | What happens |
|---|---|---|
External classic script (src) | Yes | Downloads in parallel, runs after the page is read |
Inline classic script (no src) | No | defer is ignored, and it runs at once |
type="module" script | Already deferred | Modules defer by default, so the attribute adds nothing |
| Script added by JavaScript | No | Dynamic scripts act like async unless you set script.async = false |
If a script has both defer and async, browsers that understand async use async. Pick one.
defer vs the End of the Bodyβ
For years the advice was "put your scripts just before the closing body tag." That works, because the page above is already read when the script is found. But defer is better:
| Plain script at the end of the body | defer in the head | |
|---|---|---|
| Blocks the content above it | No | No |
| When does the download start? | Late, when the parser gets there | Early, as soon as the head is read |
| Order kept | Yes | Yes |
| Easy to see all scripts at once | No | Yes |
Both let the page appear. defer simply starts the download sooner, which can finish the work sooner.
Four Bugs When Adding deferβ
Adding defer to an old page is usually safe, but these four problems are common. Each has a simple fix.
1. An inline script uses something from a deferred fileβ
<script src="/js/lib.js" defer></script>
<script>Lib.start();</script> <!-- runs at once: Lib does not exist yet -->
The inline script runs while the page is being read, before the deferred file has run. Wrap it so it waits:
<script>
document.addEventListener("DOMContentLoaded", function () { Lib.start(); });
</script>
Better still, move the code into a deferred file of its own.
2. An inline event handler calls a function that does not exist yetβ
<button onclick="openMenu()">Menu</button>
If openMenu is defined in a deferred script, a very fast click before it has run causes an error. Add the listener from the script itself instead, with addEventListener.
3. Code that expects the page to still be loadingβ
Some old code checks document.readyState === "loading". A deferred script runs when the state is "interactive", so a check like that can behave differently. Test any code that reads the ready state.
4. Code that uses document.writeβ
document.write does not work in a deferred script, because the page has already been read. Replace it with normal DOM methods such as append.
A useful trick: DOMContentLoaded still fires after deferred scripts run, so a listener added from inside a deferred script works fine. You do not need to add one if your script already runs when the page is ready.
Move an Old Page to deferβ
Paste the scripts from an old page into the helper. It lists what to change, and builds the head block in the original order. The sample is a typical old page.
Loading the helper...
The steps in real life are:
- List every script, in order.
- Add
deferto the external classic scripts, keeping their order. - Leave independent scripts such as analytics as
async. - Fix any inline script that uses a deferred library.
- Reload, and check the console for errors.
- Compare timings before and after.
What defer Does and Does Not Speed Upβ
- It helps the first paint. The page no longer waits for the script, so content can appear sooner. This improves First Contentful Paint (FCP) and often Largest Contentful Paint (LCP).
- It does not shrink the script. The browser still downloads, compiles, and runs every byte.
- It can delay
DOMContentLoaded. That event waits for deferred scripts, so it may fire later even though the page looks ready sooner. Do not judge byDOMContentLoadedalone. - It does not remove the cost of running. A heavy deferred script still keeps the main thread busy, which can hurt Interaction to Next Paint (INP). Send less code too.
Checking in DevToolsβ
- Open DevTools, then Network, filter by JS, and reload.
- In the Waterfall, the deferred script should start downloading early, alongside the stylesheet, not after it.
- Open the Performance panel and record a load. The script should run after the page content appears, not before.
- Check the Console for errors such as "is not defined", which point to a dependency problem.
- Compare First Contentful Paint and Largest Contentful Paint before and after, in Lighthouse or the Performance panel.
Best Practicesβ
- Use
deferfor your own external scripts by default. - Put them in the head, so they are found early.
- Keep the order that dependencies need.
- Do not rely on inline scripts that use deferred code. Wrap them or move them.
- Use
addEventListener, not inlineonclickhandlers, for code that lives in deferred files. - Use
asynconly for independent scripts. - Test the page after every change, and with a slow connection.
- Send less code, because
deferdoes not make it cheaper to run.
Quick Checklistβ
- External scripts that your page needs use
defer - They sit in the head, in dependency order
- No
deferon inline scripts - No inline script uses something from a deferred file before it has run
- No
document.writein deferred code - Buttons and links do not depend on a function that may not exist yet
- The console shows no "is not defined" errors
- FCP and LCP checked before and after
Security and Privacy Notesβ
deferdoes not change trust. A deferred script has the same power as a plain one. Load scripts only from sources you trust.- Use integrity hashes for fixed files. For a script from a CDN that does not change, add
integrityandcrossorigin="anonymous", so the browser refuses a file that has been altered. - A content security policy applies to deferred scripts too. It can block inline code and inline event handlers, which is another reason to use
addEventListenerand separate files. - Do not defer your way around consent. A deferred analytics or advertising script still contacts a third party and may collect data. If you need consent first, do not load the script until it is given. This is not legal advice, so check the rules that apply to you.
- Do not build script URLs from untrusted input.
Global Audience Notesβ
- Deferred scripts still run on the visitor's device. On a modest phone, a heavy bundle can keep the page unresponsive even after it appears. Send less, not just later.
- Order creates waiting. If an earlier deferred script comes from a slow or distant server, later deferred scripts wait for it. Host important scripts close to your visitors, and keep third-party scripts out of the deferred queue where you can.
- A blocked or failed script (a service unavailable in some regions, for example) should not take down your page. Keep your core content independent of third-party scripts.
- Test on slow networks, since the gap between "page appears" and "page works" gets longer there. Make sure the page is useful in between.
Common Mistakes to Avoidβ
- Adding
deferto an inline script, where it does nothing. - Inline code that uses a deferred library straight away.
- Inline
onclickcalling a function from a deferred file. - Mixing
deferandasyncon the same tag. - Putting scripts in the wrong order, so a dependency runs second.
- Expecting
deferto make the script smaller. - Judging by
DOMContentLoadedinstead of the first paint. - Using
document.writein deferred code. - Not testing after the change.
- Deferring a script that must run first, such as one that sets a theme before the page paints, without a plan.
Practice Timeβ
- In the Run Order Lab, add
defertolib.jsonly. What breaks, and why? - Fix it with the DOMContentLoaded checkbox.
- Add
deferto both scripts. How many scripts now hold up the heading? - Paste an old page of your own into the migration helper. How many changes does it suggest?
- Apply them, and reload with the console open.
- Find an inline
onclickin a page you built, and replace it withaddEventListener. - Record a Performance trace before and after, and compare when the content appears.
- Bonus: put an earlier deferred script behind a slow network throttle, and see how it delays the later ones.
Quick Recapβ
Click a question to check your answer.
1. When does a deferred script download, and when does it run?
It downloads in the background as soon as the browser finds it, and runs after the HTML has been fully read, just before DOMContentLoaded.
2. In what order do deferred scripts run?
In the order they appear in the HTML, even if a later one finishes downloading first.
3. Does defer work on inline scripts?
No. It only works on external classic scripts, with a src. Module scripts are already deferred.
4. What is the most common bug after adding defer?
An inline script that uses something from a deferred file. It runs first, so the library is not defined yet. Wrap it in a DOMContentLoaded listener, or move it into a deferred file.
5. Why is defer in the head better than a script at the end of the body?
Both let the content appear, but defer is found earlier, so the download starts sooner.
6. What does defer not fix?
The size and running cost of the script. A heavy deferred script still keeps the main thread busy, which can hurt responsiveness.
Key Takeawaysβ
deferdownloads in parallel and runs after the page is read.- Deferred scripts keep their order, which makes them safe for dependencies.
- It only applies to external classic scripts. Modules are deferred already.
- Watch for inline scripts and inline handlers that use deferred code.
- It helps the first paint, not the size of the script.
- Put deferred scripts in the head, so they are found early.
- Test after every change, and keep the code you send small.
Next up: Async, where you will meet the other loading mode, and learn when "run as soon as it arrives" is the right choice.