Script Loading and Performance
If images are the heaviest files on a page, JavaScript is the most expensive. A 100 KB image costs time to download, and then the browser simply paints it. A 100 KB script costs time to download, then to read and compile, and then to run, and all of that running happens on the same single thread that responds to the visitor's taps and clicks.
The basics of the script element, with defer, async, and modules, are in the earlier Script lesson. This lesson looks at scripts through a performance lens: what the browser does with them, what they cost, and how to load them without hurting the page.
What You Will Learnβ
- What the browser does when it meets a script
- Why a plain script blocks the page
- How loading modes change the order scripts run in
- Why JavaScript costs more than its download size suggests
- Practical ways to send less, split, and delay scripts
- How to handle third-party scripts carefully
- How to measure script cost in DevTools
The Big Ideaβ
Scripts have two jobs on the loading timeline: getting there (download) and getting done (run). Plain scripts make the page wait for both. defer and async let the page carry on while the download happens.
- HTML Code
- Script Order Lab
<head>
<meta charset="utf-8">
<title>The Bread Bin</title>
<link rel="stylesheet" href="/site.css">
<!-- Your own scripts: download now, run in order after the page is read -->
<script src="/js/lib.js" defer></script>
<script src="/js/app.js" defer></script>
<!-- An independent script: run whenever it arrives -->
<script src="/js/analytics.js" async></script>
</head>
<body>
<h1>Fresh bread, every morning</h1>
</body>
Blue is the download, green is the script running.
- Page can first appear at: about 300 ms
- All scripts finished by: 630 ms
- app.js needs lib.js first: OK, lib.js ran first.
This is a simplified model with fixed sizes. The scripts are found at 100 ms, the rest of the page takes 200 ms to read, and styles are ignored. Real pages differ, so measure your own.
In the lab, set all three scripts to plain and see when the page can first appear. Then set them to defer. Finally, set all three to async, and watch what happens to app.js, which needs lib.js first.
What the Browser Does with a Scriptβ
For every script, the browser goes through the same steps:
- Find it. The browser notices the
scripttag in the HTML. - Fetch it. It downloads the file (unless it is inline).
- Parse and compile it. It reads the code and prepares it to run.
- Run it. The code executes on the main thread, the same one that builds the page and handles clicks.
A plain script does all four steps while the HTML parser waits. Nothing after it on the page is read until it has finished. That is why a plain script in the head can leave visitors staring at a blank screen.
defer and async move steps 2 and 3 into the background. They differ in step 4, which you will explore in depth in the next two lessons, Defer and Async.
Order and Dependenciesβ
When scripts depend on each other, the order they run in matters.
| Mode | Runs when | Order | Safe for dependent scripts? |
|---|---|---|---|
| Plain | Straight away, page waits | In page order | Yes, but blocks the page |
defer | After the page is read | In page order | Yes |
async | As soon as it arrives | Whoever arrives first | No |
In the lab, the app code needs the library first. With defer on both, the order is kept. With async on both, the smaller file arrives first, runs first, and breaks. This is one of the most common bugs after adding async. If order matters, use defer (or modules), and save async for scripts that depend on nothing and that nothing depends on.
Dynamically inserted scripts, created with document.createElement("script"), behave like async by default. Set script.async = false if you need them to run in order.
Why JavaScript Costs More Than You Thinkβ
Two scripts of the same size can cost very different amounts. Downloading is only part of the bill. After the download, the browser must parse, compile, and run the code, and a slow phone does that much slower than a fast laptop. Try it:
- Total to download: 410 KB, about 656 ms
- Time the main thread is busy running it: about 492 ms
While the main thread is busy, taps, clicks, and typing have to wait. That waiting is what Interaction to Next Paint (INP) measures.
These numbers use made-up, illustrative assumptions: 0.3 ms of work per KB on a fast laptop, multiplied for slower devices. Real costs depend on what the code does. Use them to compare options, not to predict your page.
The lesson from the lab is not the exact numbers (they are illustrative), but the pattern: the same scripts that feel instant on your development machine can keep a modest phone busy for a long time, and anything you add makes it worse.
Six Ways to Make Scripts Cheaperβ
1. Send lessβ
The fastest script is the one you do not load. Remove libraries you barely use, check whether a feature needs JavaScript at all (HTML and CSS can do a lot, such as details, dialog, and CSS animations), and delete old code. Build tools can also remove unused code ("tree shaking") and shrink files ("minification"), and servers can compress them.
2. Do not blockβ
Use defer for your own scripts, and async for independent ones. This is the single biggest and cheapest improvement for most pages.
3. Split big filesβ
Instead of one huge file, send only what the current page needs, and load the rest when it is required. Modern JavaScript can do this with a dynamic import():
document.querySelector("#open-chart").addEventListener("click", async function () {
const mod = await import("/js/chart.js");
mod.drawChart();
}, { once: true });
The chart code is downloaded only if someone asks for the chart.
4. Load non-essential scripts laterβ
A chat widget or survey does not need to be ready the moment the page appears. You can load it once the page has finished loading and the browser is idle:
function loadScript(src) {
const s = document.createElement("script");
s.src = src;
s.async = true;
document.head.appendChild(s);
}
window.addEventListener("load", function () {
if ("requestIdleCallback" in window) {
requestIdleCallback(function () { loadScript("/js/chat.js"); });
} else {
setTimeout(function () { loadScript("/js/chat.js"); }, 2000);
}
});
The check for requestIdleCallback is there because not every browser supports it.
5. Load on interactionβ
Better still, load a script only when the visitor shows they want it, such as on hover or click. The click-to-load pattern in the Lazy Loading lesson is the same idea for embeds.
6. Break up long tasksβ
A script that runs for a long time without a pause keeps the main thread busy, and the page cannot respond. Browsers treat any task over about 50 milliseconds as "long". Splitting heavy work into smaller pieces lets clicks and typing get through in between. This is an advanced topic, but it is worth knowing why a fast-loading page can still feel sluggish.
Third-Party Scriptsβ
Analytics, ads, chat, social buttons, and tag managers often add more JavaScript than your own code, and you do not control them. Treat each one as a purchase:
- Is it worth its cost? Ask what it brings, and what it costs in time and data.
- Load it with
asyncordefer, never plain. - Load it late if it does not need to be ready at once.
- Replace it with a lighter option or a click-to-load version where you can.
- Review them regularly. Old tags tend to pile up.
- Make sure the page works if it fails. Visitors with blockers, slow networks, or strict regions may never load it.
Where Do the Events Fire?β
You will hear two names often:
| Event | When it fires | Waits for |
|---|---|---|
DOMContentLoaded | The HTML has been read and deferred scripts have run | Scripts, not images |
load | Everything, including images and styles, has finished | All files |
Scripts that only need the page structure can run on DOMContentLoaded, and defer scripts run just before it. Do not make visitors wait for the load event to see or use your page.
Measuring Script Costβ
- Open DevTools, then Network, and filter by JS. Sort by size to see the heaviest files.
- Open the Performance panel, record a page load, and look for long red-marked tasks on the main thread. Click one to see which script caused it.
- Open the Coverage tool (in the DevTools menu) to see how much of each script was never used on this page.
- Run Lighthouse, and read the suggestions about unused JavaScript and long main-thread work. It reports a lab number called Total Blocking Time (TBT).
- Look at your field data for Interaction to Next Paint (INP) in PageSpeed Insights or Search Console, where it is available, because that is what your visitors actually feel.
- Test with a CPU slowdown and a slow network turned on in DevTools.
Best Practicesβ
- Send less JavaScript. Remove what you do not use.
- Use
deferfor your own scripts, andasyncfor independent ones. - Never use
asyncfor scripts that depend on each other. - Split large bundles, and load heavy features on demand.
- Load non-essential scripts late, or on interaction.
- Treat third-party scripts as a cost, and review them often.
- Keep the page working if a script fails or is blocked.
- Measure on a slow phone, not only on your own laptop.
Quick Checklistβ
- No plain
scripttags withsrcin the head - Dependent scripts use
defer, notasync - Independent scripts use
asyncordefer - Unused libraries and old tags have been removed
- Large features load on demand
- Third-party scripts load late, and are reviewed
- The page still works with a script blocked
- DevTools shows no long tasks that block the first interaction
Security and Privacy Notesβ
- A script has the full power of your page. It can read what visitors type, change the page, and send data elsewhere. Load scripts only from sources you trust, and keep the list short.
- Use Subresource Integrity for fixed files. For a script from a CDN that does not change, add an
integrityhash andcrossorigin="anonymous". The browser then refuses the file if it has been altered. Do not use it for files that change at the source. - Add a Content Security Policy. A policy limits which hosts scripts may come from, and can stop injected scripts. It is a server setting, and it can also block inline scripts and inline
onloadhandlers, so test it carefully. - Third-party scripts see your visitors. Analytics, ads, and chat tools may collect data and set cookies. If you need consent before they run, do not load them until consent is given. This is not legal advice, so check the rules that apply to you.
- Never build a script URL from untrusted input, such as a query string.
- Keep dependencies updated. Old libraries can contain known security problems.
Global Audience Notesβ
- Many visitors use modest phones. Slower processors make the "run" step take several times longer than on your own device, so JavaScript hits them hardest.
- Data costs real money in many places, and scripts are often large. Smaller bundles help people on limited plans.
- Some third-party services are slow or blocked in some regions. A plain script that waits on one can freeze your page for those visitors. Always use
asyncordefer, and make sure the page works without them. - Slow networks make late scripts feel worse. Test with throttling, and design so the content shows first and extras follow.
- Do not make content depend on JavaScript when plain HTML can do the job. It is faster, and it works everywhere.
Common Mistakes to Avoidβ
- Plain scripts in the head.
- Using
asyncfor scripts that depend on each other. - Loading a huge library for one small feature.
- Never removing old third-party tags.
- Loading every feature on every page.
- Adding
deferto a script that must run before the page is read (without checking it still works). - Waiting for the
loadevent before showing or enabling the page. - Testing only on a fast laptop.
- Ignoring long tasks, so the page loads fast but feels slow.
- Letting the page depend on a third-party script that may fail.
Practice Timeβ
- In the Script Order Lab, set all scripts to plain. When can the page first appear? Now set them to defer.
- Set all three to async. What goes wrong?
- Find a combination where the page appears early and the dependency is still kept.
- In the Script Weight Lab, add the advertising tags, then switch device from laptop to low-end phone. How does the busy time change?
- Remove scripts one at a time. Which one saves the most?
- Open a page you built, and sort the Network panel by size, filtered to JS. Which file is biggest?
- Use the Coverage tool. How much of the biggest file was unused?
- Bonus: record a Performance trace and find the longest task. Which script caused it?
Quick Recapβ
Click a question to check your answer.
1. What does a browser do with a script?
It finds it, fetches it, parses and compiles it, and runs it on the main thread. A plain script makes the HTML parser wait through all of those steps.
2. Which loading mode keeps scripts in order?
defer (and modules). Deferred scripts run after the page is read, in the order they are written. async scripts run in whatever order they arrive.
3. Why does JavaScript cost more than an image of the same size?
After downloading, it must be parsed, compiled, and run on the main thread, which is slower on modest devices and delays responses to taps and clicks.
4. How can you avoid loading a heavy feature up front?
Split it into its own file and load it on demand, with a dynamic import(), on interaction, or when the browser is idle.
5. How should third-party scripts be handled?
Only load ones that are worth their cost, use async or defer, load them late where possible, review them often, and make sure the page works if they fail.
6. How do you see which scripts are expensive?
Use the Network panel to see sizes, the Performance panel to find long tasks, the Coverage tool to see unused code, and Lighthouse and field data for the overall effect.
Key Takeawaysβ
- JavaScript is the most expensive file type: download, compile, and run.
- Plain scripts block the page. Use
deferandasync. - Order matters.
deferkeeps it,asyncdoes not. - Send less, split, and delay what is not needed at first.
- Third-party scripts are a cost and a risk. Review them often.
- Mind security: trust the source, use integrity hashes for fixed files, and consider a content security policy.
- Test on a slow phone, and look at INP as well as load time.
Next up: Defer, where you will see exactly how deferred scripts behave, and when they are the right choice.