Why a big JSON file freezes the page
A web page does almost all of its work on one thread, the main thread. While that thread parses JSON or draws thousands of rows, it cannot answer a click. We load 10,000 and 100,000 orders into a React page, click a button while it works, and find which step really freezes it.
What you will be able to do
- Name the four steps between “the response arrived” and “the user sees rows”
- Explain why one busy main thread makes clicks wait
- Measure download, parse, render, layout and paint time in a real browser
- Read a long task and a worst click wait
- Show that rendering fewer rows removes the freeze, while a faster parse would not
The idea, in plain English
A browser tab runs your JavaScript, React, and the work of drawing the page - style, layout and paint - on one thread: the main thread. It does one thing at a time. When the user clicks, the click goes into a queue and is handled only when the thread finishes its current job. A job longer than 50 ms is called a long task, and the user feels it as a frozen page.
Showing a big JSON file takes four steps on that thread: download the text, JSON.parse turns the text into objects, React builds the rows and puts them into the DOM, and the browser lays out and paints them. Most people blame JSON.parse. In this lesson we time each step separately and find that, for a table of orders, the DOM is far more expensive than the parse.
How we measured: a real browser engine - headless Chromium 159.0.8154.6, driven by playwright-core 1.65.1 - with React 19.2.3 bundled by esbuild 0.28.1, on an Intel Core i5-4200U laptop (4 threads, 7 GB RAM). Every case ran 5 times; the numbers are the medians. A faster computer gives smaller numbers, so compare the steps with each other, not with your own machine.
Worked example: Load 10,000, 100,000 and 1,000,000 order records into a React page, time each step, and click a button every 100 ms while the page works.
1 - Download and parse
The text arrives and JSON.parse turns it into 100,000 objects. This part is short.
Median of 5 runs in headless Chromium. Real results from run.mjs.
Words you will see in this lesson
A few browser words, in plain English.
Main threadThe one worker in a browser tab that runs your JavaScript, React, layout and paint - one job at a time.JSON.parseTurns JSON text into JavaScript objects and arrays.DOM nodeOne element on the page, such as a <tr> or a <td>. The browser must store, lay out and paint each one.Render (React)React calls your components and creates or updates the DOM nodes they describe.LayoutThe browser works out the size and position of every node.PaintThe browser draws the pixels of the nodes on screen.Long taskAny job on the main thread longer than 50 ms. During it the page cannot respond.Click waitTime from the moment the user clicks to the moment your click handler runs.MedianThe middle value of several runs. One slow or fast run cannot move it much.An everyday example: one cashier
- A small shop has one cashier. She scans items, takes money and answers questions - one thing at a time.
- A customer arrives with 100,000 items. While she scans them, nobody else gets served - not even someone who only wants to ask where the door is.
- Scanning faster helps a little. Not scanning items nobody asked for helps much more.
- The cashier is the main thread, the items are your rows, and the waiting customer is the user’s click.
The test data: order records
Every lesson in this course uses the same data, so the numbers can be compared. gen.mjs writes an array of orders at three sizes. A fixed seed makes the data the same on every run:
- Each order has an id, a customer, a city, a status, a total and 1 to 3 items.
- rand() is a small seeded random number generator - the same seed always gives the same orders.
- JSON.stringify turns the array into the text a server would send.
// Generate the course's order records: orders-10000.json, orders-100000.json, orders-1000000.json
import fs from "node:fs";
const customers = ["Asha", "Ben", "Chen", "Diya", "Emil", "Fatima", "Gopal", "Hana", "Ivan", "Jaya"];
const cities = ["Hyderabad", "Pune", "Chennai", "Delhi", "Mumbai", "Kolkata"];
const statuses = ["new", "paid", "shipped", "delivered", "cancelled"];
let seed = 42; // same data every run
const rand = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
const pick = (list) => list[Math.floor(rand() * list.length)];
function makeOrders(count) {
const orders = [];
for (let id = 1; id <= count; id++) {
const items = [];
const n = 1 + Math.floor(rand() * 3);
for (let i = 0; i < n; i++) {
items.push({ sku: "SKU-" + (1000 + Math.floor(rand() * 9000)), qty: 1 + Math.floor(rand() * 4), price: Math.round(rand() * 5000) / 100 });
}
const total = Math.round(items.reduce((sum, it) => sum + it.qty * it.price, 0) * 100) / 100;
orders.push({ id, customer: pick(customers), city: pick(cities), status: pick(statuses), total, items });
}
return orders;
}
for (const count of [10_000, 100_000, 1_000_000]) {
seed = 42;
const text = JSON.stringify(makeOrders(count));
fs.writeFileSync("public/orders-" + count + ".json", text);
console.log("orders-" + count + ".json " + (text.length / 1024 / 1024).toFixed(1) + " MB");
}orders-10000.json 1.6 MB
orders-100000.json 16.3 MB
orders-1000000.json 163.5 MB{
"id": 1,
"customer": "Ben",
"city": "Hyderabad",
"status": "paid",
"total": 217.94,
"items": [
{
"sku": "SKU-5678",
"qty": 4,
"price": 34.94
},
{
"sku": "SKU-7777",
"qty": 3,
"price": 26.06
}
]
}Example 1 - the page under test
app.jsx is an ordinary React page: it downloads the orders, parses them and shows every order as a table row. A few lines of timing code mark the end of each step:
- mark(name) saves performance.now() - a precise clock in milliseconds - under a name, and logs it.
- res.text() and JSON.parse(text) are timed separately, so download and parse get their own numbers. (res.json() does both at once.)
- useLayoutEffect in OrderTable runs right after React has put every row into the DOM: that is “committed”.
- requestAnimationFrame followed by setTimeout runs just after the browser has laid out and painted the next frame: that is “painted”.
- A PerformanceObserver collects every long task the browser reports.
- ClickButton has its own state, so a click re-renders only the button - not the whole table.
- ?show=100 renders only the first 100 orders, and ?mode=parse stops after JSON.parse. We use both later.
// The page under test: download the orders, parse them, render every order as a table row.
// ?n=10000|100000|1000000 ?show=100 (render only the first 100) ?mode=parse (no render)
import { useEffect, useLayoutEffect, useState } from "react";
import { createRoot } from "react-dom/client";
const params = new URLSearchParams(location.search);
const url = "/orders-" + params.get("n") + ".json";
const show = Number(params.get("show") || Infinity);
const parseOnly = params.get("mode") === "parse";
window.timings = {};
const mark = (name) => {
window.timings[name] = performance.now();
console.log("mark " + name);
};
window.longTasks = [];
window.clicksHandledAt = [];
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) window.longTasks.push(entry.duration);
}).observe({ type: "longtask", buffered: true });
function OrderRow({ order }) {
return (
<tr>
<td>{order.id}</td>
<td>{order.customer}</td>
<td>{order.city}</td>
<td>{order.status}</td>
<td>{order.total.toFixed(2)}</td>
<td>{order.items.length}</td>
</tr>
);
}
function OrderTable({ orders }) {
useLayoutEffect(() => {
mark("committed"); // React has put every row into the DOM
requestAnimationFrame(() =>
setTimeout(() => {
mark("painted"); // the browser has laid out and painted the table
window.done = true;
}),
);
}, []);
return (
<table>
<tbody>
{orders.map((order) => (
<OrderRow key={order.id} order={order} />
))}
</tbody>
</table>
);
}
// A button the user can press while the orders load. It keeps its own state,
// so a click re-renders only the button - not the table.
function ClickButton() {
const [clicks, setClicks] = useState(0);
function handleClick() {
window.clicksHandledAt.push(performance.timeOrigin + performance.now()); // wall-clock time this click ran
setClicks((c) => c + 1);
}
return (
<button onClick={handleClick} style={{ position: "fixed", top: 0, left: 0, width: 200, height: 40 }}>
Clicked {clicks} times
</button>
);
}
function App() {
const [orders, setOrders] = useState(null);
useEffect(() => {
(async () => {
mark("start");
const res = await fetch(url);
const text = await res.text();
mark("downloaded");
const data = JSON.parse(text);
mark("parsed");
if (parseOnly) {
window.orders = data; // keep the parsed orders alive, as a real page would
window.done = true;
return;
}
setOrders(data.length > show ? data.slice(0, show) : data);
})();
}, []);
return (
<>
<ClickButton />
{orders ? <OrderTable orders={orders} /> : <p>Loading orders…</p>}
</>
);
}
createRoot(document.getElementById("root")).render(<App />);Example 2 - an impatient user
run.mjs opens the page in headless Chromium with Playwright and plays an impatient user: from the moment the download finishes, it clicks the button every 100 ms until the table is painted. These are real mouse clicks, sent the same way a real mouse would send them. This is the part of run.mjs that clicks:
- page.on("console") hears the page’s mark() messages, so the clicking starts right after “mark downloaded”.
- sentAt keeps the time each click was sent; the page keeps the time each click handler ran.
- Click wait = handler time minus send time. The worst wait is the longest the user had to wait for an answer.
- The rest of run.mjs starts a small local web server, opens a fresh page for each run, runs every case 5 times and prints the medians.
// Like an impatient user: from the moment the download finishes, click the button every 100 ms
// until the page has finished. Each click is a real mouse click; we keep the time it was sent.
const sentAt = [];
let timer = null;
page.on("console", (msg) => {
const text = msg.text();
if (text === "mark downloaded" && !timer) {
timer = setInterval(() => {
sentAt.push(Date.now());
page.mouse.click(100, 20).catch(() => {});
}, 100);
}
if ((text === "mark painted" || (text === "mark parsed" && query.includes("mode=parse"))) && timer) {
clearInterval(timer);
}
});browser 159.0.8154.6 | cpu Intel(R) Core(TM) i5-4200U CPU @ 1.60GHz x4 | ram 7 GB
n=10000 download 45 ms | parse 15 ms | render 161 ms | layout+paint 893 ms | clicks 10, worst wait 933 ms | longest task 869 ms | DOM nodes 70,010 | JS heap 18 MB
n=100000 download 209 ms | parse 162 ms | render 1,407 ms | layout+paint 10,232 ms | clicks 117, worst wait 11,364 ms | longest task 11,411 ms | DOM nodes 700,010 | JS heap 163 MB
n=100000&show=100 download 184 ms | parse 145 ms | render 10 ms | layout+paint 22 ms | clicks 1, worst wait 48 ms | longest task 147 ms | DOM nodes 710 | JS heap 34 MB
n=10000&mode=parse download 43 ms | parse 15 ms | render - | layout+paint - | clicks 0, worst wait - | longest task 0 ms | DOM nodes 9 | JS heap 5 MB
n=100000&mode=parse download 173 ms | parse 149 ms | render - | layout+paint - | clicks 1, worst wait 51 ms | longest task 151 ms | DOM nodes 9 | JS heap 33 MB
n=1000000&mode=parse download 958 ms | parse 1,701 ms | render - | layout+paint - | clicks 16, worst wait 1,604 ms | longest task 1,719 ms | DOM nodes 9 | JS heap 313 MBReading the output
- 10,000 orders (1.6 MB): JSON.parse took 15 ms. React render took 161 ms, and layout + paint took 893 ms. A click waited up to 933 ms.
- 100,000 orders (16.3 MB): JSON.parse took 162 ms. React render took 1,407 ms, and layout + paint took 10,232 ms. The worst click waited 11,364 ms - the page was frozen for 11.4 seconds.
- The longest single task at 100,000 orders was 11,411 ms. The limit for a long task is 50 ms.
- Each order is 7 DOM nodes (one <tr> and six <td>), so 100,000 orders became 700,010 nodes.
- Ten times more orders made every step roughly ten times slower. The work grows with the number of rows.
Where the time goes at 100,000 orders
Put the four steps side by side. The parse is a small part; drawing the rows is almost all of it:
Download (local server)209 msJSON.parse162 ms (1.3% of the total)React render1,407 ms (11.7%)Layout + paint10,232 ms (85.2%)Tip: Our server runs on the same laptop, so the download is fast. Over a real network a 16.3 MB download takes much longer - but downloading does not block the main thread. The page can still answer clicks while it waits for the network.
Trap: blaming JSON.parse
A common first fix is to make the parse faster - a faster JSON library, or a smaller file. But the parse was only 1.3% of the time. To test where the freeze really comes from, keep the same 16.3 MB file and the same parse, and only change how many rows go into the DOM:
- The parse did not change: 162 ms before, 145 ms after.
- The worst click wait fell from 11,364 ms to 48 ms.
- DOM nodes fell from 700,010 to 710.
- What is left is the parse itself: the longest task, 147 ms, is the JSON.parse call.
setOrders(data); // 100,000 rowssetOrders(data.length > show ? data.slice(0, show) : data); // show = 100n=100000 download 209 ms | parse 162 ms | render 1,407 ms | layout+paint 10,232 ms | clicks 117, worst wait 11,364 ms | longest task 11,411 ms | DOM nodes 700,010 | JS heap 163 MB
n=100000&show=100 download 184 ms | parse 145 ms | render 10 ms | layout+paint 22 ms | clicks 1, worst wait 48 ms | longest task 147 ms | DOM nodes 710 | JS heap 34 MBWatch out: Showing only the first 100 orders is a test, not a fix - users still need to reach the other 99,900. Virtual scrolling (Lesson 2.2) and pagination (Lesson 2.3) keep the DOM this small while every order stays reachable.
1,000,000 orders: now the parse freezes too
With ?mode=parse the page downloads and parses the orders but draws nothing. This shows the cost of the parse alone:
- 10,000 orders parse in 15 ms - no long task at all.
- 100,000 orders: 149 ms - a long task, but short.
- 1,000,000 orders (163.5 MB): 1,701 ms, and a click waited up to 1,604 ms - with not one row drawn.
- The parsed orders took 313 MB of JavaScript memory.
- We did not try to draw 1,000,000 rows: that would be about 7,000,000 DOM nodes, and 100,000 rows already froze the page for 11.4 seconds.
- At this size even JSON.parse is a problem. Moving it off the main thread (Lesson 3.1) and streaming the file (Lesson 3.3) deal with that.
n=10000&mode=parse download 43 ms | parse 15 ms | render - | layout+paint - | clicks 0, worst wait - | longest task 0 ms | DOM nodes 9 | JS heap 5 MB
n=100000&mode=parse download 173 ms | parse 149 ms | render - | layout+paint - | clicks 1, worst wait 51 ms | longest task 151 ms | DOM nodes 9 | JS heap 33 MB
n=1000000&mode=parse download 958 ms | parse 1,701 ms | render - | layout+paint - | clicks 16, worst wait 1,604 ms | longest task 1,719 ms | DOM nodes 9 | JS heap 313 MBTwo surprises while measuring
- One click can slip through. In our first version, run.mjs sent a single click after the download. At 10,000 orders it was answered quickly, although a long task froze the page right after it. The reason: after setOrders(), React renders in a new task, and the click was handled in the gap between the parse and the render. One click measures luck - so we click every 100 ms and report the worst wait.
- Clicks can make the freeze longer. In an early version the click counter was state in App. Every click re-rendered App - and with it the whole table - so layout + paint took more than twice as long. Moving the counter into its own ClickButton component fixed it. Keeping state close to where it is used is the subject of Lesson 4.2.
Measuring the main thread
Time a stepMilliseconds, with fractions.
const t0 = performance.now(); work(); performance.now() - t0
Long tasksEvery job over 50 ms.
new PerformanceObserver(cb).observe({ type: "longtask", buffered: true })DOM sizeHow many elements the page holds.
document.getElementsByTagName("*").lengthJS memoryChrome only; precise with --enable-precise-memory-info.
performance.memory.usedJSHeapSize
After the DOM updateReact has committed the rows.
useLayoutEffect(() => { ... }, [])After paintThe next frame has been drawn.
requestAnimationFrame(() => setTimeout(done))
Try it yourself
The code does not change. Swap the content string and the program does something else entirely.
“Open /?n=100000&show=1000, then show=10000. How do DOM nodes and the worst click wait grow?”
“Remove the city and status cells from OrderRow. Does layout + paint for 100,000 orders shrink by about the same share as the DOM nodes?”
“Replace res.text() + JSON.parse with res.json(). Which two numbers merge into one, and is the total different?”
“Change the click interval in run.mjs from 100 ms to 1,000 ms. Does the worst click wait at 100,000 orders change?”
What usually goes wrong
At 100,000 orders the parse was 162 ms out of more than 12.0 seconds. Measure before choosing a fix.
100,000 orders became 700,010 DOM nodes, and a click waited 11,364 ms.
A single click can land between two tasks and look fast. Click repeatedly and report the worst wait.
A click counter in App re-rendered the whole table on every click.
✗ function App() { const [clicks, setClicks] = useState(0); ... <OrderTable /> }✓ function ClickButton() { const [clicks, setClicks] = useState(0); ... }Timings move from run to run. Run each case several times and use the median.
Best practices
- Time each step separately: download, parse, render, layout + paint.
- Watch long tasks: any task over 50 ms is time the user cannot interact.
- Count DOM nodes - it is often the number that explains a slow page.
- Test with realistic data sizes, not only with ten rows.
- Report medians of several runs, and name the machine and browser you measured on.
Practice
Write these yourself before opening anything. Getting them wrong first is most of how this sticks.
Add a “typing” test to run.mjs: instead of clicking, type a letter into an <input> every 100 ms while 100,000 orders load, and report the worst delay between a key press and the input’s onChange.
Show hintHide hint
Use page.keyboard.press("a") after focusing the input, and push performance.timeOrigin + performance.now() from onChange, as ClickButton does.
Measure 30,000 and 60,000 orders as well (add them to gen.mjs and CASES). Plot the worst click wait against the number of orders. Is it a straight line?
Find the step that hurts
Take a page from one of your own projects that shows a big list or table, and split its loading time into download, parse, render and layout + paint.
- Add mark() calls (or performance.mark) after each step, as app.jsx does.
- Run it at least 5 times and report the median of each step.
- Count the DOM nodes after the page has loaded.
- Name the step that costs the most - and say which lesson of this course targets it.
Key points
- JavaScript, React, layout and paint all share one main thread; while it works, clicks wait.
- At 100,000 orders, JSON.parse took 162 ms, but render + layout + paint took 11.6 seconds.
- The worst click waited 11,364 ms with every row drawn and 48 ms with 100 rows drawn - same file, same parse.
- At 1,000,000 orders the parse alone blocked clicks for up to 1,604 ms.
- Find the slow step first; then choose the approach that targets it.
Quick check before you move on
Interview questions
A page that shows a large JSON response freezes. How do you find out why?
Measure each phase separately - network, JSON.parse, React render or commit, and layout/paint - with performance marks, the Performance panel or a long-task observer, and count DOM nodes. Then fix the dominant phase: usually DOM size (virtualise or paginate); for very large payloads, parse off the main thread or stream.
What is a long task and why does it matter?
A main-thread task longer than 50 ms. While it runs, the browser cannot process input or paint, so it directly causes input delay and poor responsiveness (INP).
Does res.json() block the main thread?
Waiting for the body does not, but turning it into JavaScript objects does: the objects must be created on the main thread, so for very large payloads it causes a long task, just like JSON.parse.
Quiz
- 1.
Why does a click wait while the page renders a big table?
- 2.
Showing only 100 rows kept the same file and the same parse. Why did the click wait drop so much?
- 3.
Why does run.mjs click every 100 ms instead of once?
- 4.
When does JSON.parse itself become the problem?
Comments
Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.
Loading comments...