JavaScript Performance Optimization: Finding Long Tasks, Unused Code and Main-Thread Bottlenecks
Download cost and execution cost are different problems with different fixes. Why halving your bundle can change nothing.
In short
There are two completely different JavaScript performance problems, and conflating them is why so much optimisation work produces no measurable result:
Download cost — how many bytes travel over the network. Fixed by compression, minification, splitting and removing code.
Execution cost — how long the browser spends parsing, compiling and running that code on the main thread. Fixed by running less code, running it later, and breaking it up.
They are not proportional. A 50 KB script that blocks the main thread for 400 ms hurts responsiveness far more than a 500 KB script that runs briefly and then sleeps. A site can halve its bundle size and feel exactly as slow.
So the first question is not "how big is my JavaScript" but "what is it doing, and when".
Why execution is the expensive half
The main thread is where the browser parses HTML, calculates styles, lays out the page, paints it, and runs all your JavaScript. It does one thing at a time.
While a script is running, the browser cannot respond to a tap, cannot paint a new frame, and cannot get on with anything else. A script that runs for 400 ms is 400 ms during which the page is frozen, regardless of how quickly it downloaded.
And this is dramatically worse on phones. A mid-range device runs the same JavaScript several times slower than a development laptop, and throttles further as it heats up. The script that takes 80 ms on your machine may take 350 ms in a visitor's hand.
Finding out what is actually slow
Step 1 — profile with throttling
- Chrome DevTools → Performance.
- Set CPU to 4x slowdown. This matters more than network throttling here.
- Record a page load.
Step 2 — read the long tasks
Any task over 50 ms is a long task, marked with a red triangle in the recording. Hover one and it names the script responsible.
What you should see: a handful of long tasks, usually dominated by two or three scripts. Those are your targets. If the longest tasks belong to third-party domains, your problem is not your own code.
Step 3 — see where the time goes by script
Open the Bottom-Up view and group by URL. This gives you milliseconds of execution per file, which is the number that matters and the one bundle-size reports never show you.
Step 4 — find code that is never used
DevTools → Coverage panel (Ctrl+Shift+P, "Show Coverage"), then reload. It shows how much of each file was executed.
Read the result carefully: "unused" means not executed during this load. Code that runs when someone opens a menu is counted as unused. It is a guide to what to split, not a list to delete.
Reducing download cost
The easy half, and worth doing, but do not expect it to fix responsiveness.
Minify and compress. Minification strips whitespace and comments; Brotli compresses the result. Both reduce bytes, neither reduces execution time. Most frameworks minify in production builds by default.
Split by route. Each page should download what it needs, not what the whole site needs. A product page should not carry the checkout code.
// Loaded only when the visitor actually opens the gallery
button.addEventListener('click', async () => {
const { openGallery } = await import('./gallery.js');
openGallery();
});
Import only what you use, and check it worked. Tree shaking is defeated by side effects, dynamic property access and packages not shipped as ES modules — so a "tree-shakeable" library can still arrive whole. Verify in the Coverage panel rather than trusting the claim.
Audit your dependencies. A date library, a utility library and a carousel can easily outweigh your own code. Ask what each is doing for you.
Reducing execution cost
The half that moves responsiveness.
Defer what is not needed immediately
<!-- Blocks HTML parsing: the page cannot render past this point -->
<script src="/app.js"></script>
<!-- Downloads in parallel, runs after parsing, keeps order -->
<script src="/app.js" defer></script>
<!-- Downloads in parallel, runs as soon as it arrives, order not guaranteed -->
<script src="/analytics.js" async></script>
Use defer for anything that touches the page and needs to run in order. Use async for independent scripts like analytics. A script with neither blocks the parser, and that is almost never what you want.
Break up long tasks
A single long loop cannot be interrupted, so a tap during it waits. Processing in chunks and yielding lets the browser handle input in the gaps.
// One long task: input is ignored for its whole duration
for (const row of rows) render(row);
// Chunked: the browser gets a turn between batches
async function renderAll(rows) {
for (let i = 0; i < rows.length; i++) {
render(rows[i]);
if (i % 50 === 49) await new Promise((r) => setTimeout(r, 0));
}
}
Do the urgent part first
Inside an event handler, update what the visitor needs to see, then let the browser paint, then do the rest.
addToCart.addEventListener('click', () => {
// Immediate, visible feedback
badge.textContent = String(count + 1);
// Everything else after the next paint
requestAnimationFrame(() => {
setTimeout(() => {
syncWithServer();
trackEvent();
refreshRecommendations();
}, 0);
});
});
Avoid layout thrashing
Reading a layout property immediately after writing a style forces the browser to recalculate layout on the spot. In a loop, this is catastrophic.
// Forces a layout recalculation on every iteration
items.forEach((el) => {
el.style.width = '100px';
console.log(el.offsetHeight);
});
// Batch: all reads, then all writes
const heights = items.map((el) => el.offsetHeight);
items.forEach((el, i) => { el.style.width = `${heights[i]}px`; });
Move heavy work off the main thread
Computation that does not touch the DOM can run in a Web Worker, leaving the main thread free to respond.
const worker = new Worker('/parse-worker.js');
worker.postMessage(largePayload);
worker.onmessage = ({ data }) => render(data);
Workers are worth the complexity for genuinely heavy work — parsing large data, image processing, search indexing. They are not worth it for trivial tasks.
Load features on interaction
The largest execution savings usually come from not running code at all. A chat widget, a video player, a complex filter UI — all can wait until someone wants them.
Platform differences
Shopify. Theme JavaScript is yours; app scripts are not. In practice most execution time on a Shopify store belongs to apps, so the work is an app audit rather than a code change. Theme-side, the common wins are deferring scripts and loading template-specific code conditionally.
WordPress and WooCommerce. Plugins enqueue scripts site-wide by default, so pages run code for features they do not have. Conditional dequeuing per template is usually the single largest available win.
Custom and headless builds. Hydration is the usual cost: the page looks finished while the framework attaches behaviour, so early taps are ignored. Reduce how much needs hydrating, prioritise what is on screen, and prefer server-rendered interactivity where it is enough.
Hosted builders. You cannot change the platform's own JavaScript. Your lever is how many apps, widgets and animations you add.
Common mistakes
Measuring bytes instead of milliseconds. The central mistake of this whole topic.
Minifying and expecting responsiveness to improve.
Profiling without CPU throttling, on a fast machine, and concluding there is nothing to fix.
Deleting code from a Coverage report. "Unused" means "not run during this load" — interaction code is counted as unused.
Deferring a script the page needs immediately, so the first interaction does nothing.
Code splitting without measuring. Splitting adds requests and can move execution to a worse moment.
Writing a Web Worker for trivial work, adding complexity and message-passing overhead for no gain.
Ignoring third parties because they are not your code. They run on your main thread and your visitors experience them as your site.
Verification
- Re-profile with the same CPU throttling and compare total blocking time and the number and length of long tasks.
- Compare execution time per script in the Bottom-Up view, which proves the specific thing changed.
- Check the feature still works. The most common regression here is a handler that is now fast because it no longer does something necessary.
- Test on a real mid-range phone, not just emulation. Emulated CPU throttling approximates slow hardware imperfectly.
- Check LCP and CLS. Deferred code that inserts content later causes layout shift.
- Then watch field INP over four weeks. Lab proves the mechanism; field proves visitors benefited.
When it still does not improve
- Smaller bundle, same responsiveness → your cost was execution, not download, and probably not in your own bundle. Look at third parties and hydration.
- Long tasks remain after splitting → you moved code, you did not reduce work. Find what the remaining task is doing.
- It is fine in the lab, poor in the field → your hardware is kinder than your visitors'. Segment field data by device class.
- A third-party script dominates and you cannot change it → the decision becomes commercial: does the feature justify the cost? Measure it so the answer is informed.
- Hydration is the cost and you cannot remove the framework → reduce what hydrates, hydrate visible content first, and consider server-rendering the parts that do not need interactivity.
Keeping it fixed
JavaScript grows. Every feature adds some, every dependency adds more, and nobody notices a 30 ms regression.
Three habits: set a budget on total JavaScript and on total blocking time, and check it before release rather than after; require a measurement before any new dependency or third-party script is added; and monitor field INP so a regression is something you see rather than something a customer reports.
Frequently asked questions
Will reducing my JavaScript bundle size make my site faster?
It reduces download time, which is only half the problem. Execution time — parsing, compiling and running the code on the main thread — is usually the half that affects how the site feels. A 50 KB script that blocks the thread for 400 ms hurts more than a 500 KB script that runs briefly.
What is a long task?
Any piece of work occupying the main thread for more than 50 milliseconds. While it runs the browser cannot respond to a tap or paint a frame, so long tasks are the main cause of a page that feels frozen. They appear marked with red triangles in a Performance recording.
What is the difference between defer and async?
Both download in parallel without blocking HTML parsing. defer runs scripts after parsing, in document order — use it for anything that touches the page. async runs each script as soon as it arrives, order not guaranteed — use it for independent scripts like analytics. A script with neither blocks the parser.
Can I delete the unused JavaScript the Coverage panel reports?
Not directly. "Unused" means not executed during that particular load, so code that runs when someone opens a menu or adds to cart is counted as unused. Treat it as a guide to what to split and load later, not as a delete list.
Should I use a Web Worker?
Only for genuinely heavy computation that does not touch the DOM — parsing large data, image processing, search indexing. For trivial work, the message-passing overhead and added complexity are not worth it.
Why is my site fine on desktop but sluggish on mobile?
A mid-range phone runs the same JavaScript several times slower than a development laptop, and throttles further as it heats up. Always profile with CPU throttling, and ideally test on a real mid-range device.
References
- Optimize long tasks — web.dev
- Find unused JavaScript and CSS with the Coverage tool — Chrome DevTools
- Using Web Workers — MDN
- Script loading: defer and async — MDN