On Tuesday, TinyTickets shipped three changes. The analytics script got a new version with heatmaps, which Leo had asked for. Nina added the payment provider’s script to every page, as the provider’s guide asks. Omar added a button that finds the best two seats.
On Thursday, Leo opened the Midsummer Lights page on his phone. It stayed white for two seconds. When the Buy button appeared, his first tap did nothing.
“Last week this page was quick,” Leo wrote. “What did we add?”
“Two scripts we didn’t write,” Maya wrote back.
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
This module is about JavaScript as the browser pays for it: bytes to download, then work to parse, compile and run on the main thread. You’ll measure two third-party scripts on their own, then decide where and when each one may load. Then you’ll add a bundler to TinyTickets’ own code, read what it ships, and remove what nobody runs at load.
After this module, you can:
- say what a script costs after its last byte arrives, which part runs on the main thread, and find each part in a trace
- measure one third-party script’s cost on its own, with the Performance panel’s grouping by party and request blocking
- load a third-party script only on the pages and at the moment it’s needed, and name what each way of delaying it costs
- read a bundle with a bundle analysis and the Coverage panel, and shrink it with tree shaking and code splitting
- give bundled files hashed names and cache them for a year, and say what that changes on a second visit
What buyers saw after Tuesday’s release
Maya’s endpoint had a week of lines from before the release and a week from after. On show pages, from phones, LCP at the 75th percentile went from 2.3 s to 3.1 s, over 1,280 page loads after the release. INP went from 120 ms to 310 ms, over 4,060 lines.
The INP lines said more, because vitals.js sends the longest script of the slowest interaction (Module 5). In 2,410 of the 4,060 lines it was the payment provider’s script. In 1,180 it was the analytics script. Not one of these lines came from a script TinyTickets wrote.
CrUX didn’t show it yet, because its 28-day window held only one week from after the release.
Pause and predict. The two new scripts are 267 KB and 367 KB, and the server sends them compressed, as 66 KB and 91 KB. On the phone profile, which costs the show page more: downloading them, or running them? Write down a guess for each, in milliseconds.
Reproduce Tuesday’s release in the lab
The lab app is Module 6’s, with Tuesday’s three changes and two changes to the server. The finished code for this module is in the course repository, folder module-07/.
Two changes to the server
Real third parties send their files compressed, read requests from other sites, and receive beacons. So the lab server now does all three. In server.js, import gzipSync and add .json to the types:
import { gzipSync } from 'node:zlib';
'.json': 'application/json',
In serveFile(), replace the last two lines of the try block, so every file except the pictures goes out gzip-compressed:
// Text goes out compressed, as a real server or CDN sends it.
const gzip = !['.jpg', '.avif'].includes(extname(path)) && /\bgzip\b/.test(req.headers['accept-encoding']);
if (gzip) Object.assign(headers, { 'Content-Encoding': 'gzip', Vary: 'Accept-Encoding' });
res.writeHead(200, headers);
res.end(gzip ? gzipSync(body) : body);
Replace the last createServer call, the one for the third parties:
createServer((req, res) => {
// The fakes send beacons here. A real provider would store them; the lab drops them.
if (req.method === 'POST') return res.writeHead(204).end();
// Pages on localhost:8080 may read these responses, as they may a real provider's.
res.setHeader('Access-Control-Allow-Origin', '*');
return serveFile(req, res, thirdParty);
}).listen(8081);
The compression changes the Module 6 pages very little. In three loads, the show page had FCP 1,320–1,328 ms and LCP 1,336–1,352 ms, and the seat map’s LCP was 3,632–3,712 ms.
Two heavier fakes
Real analytics and payment scripts are large, minified libraries, and they do setup work as they load. The new third-party/make-fakes.js writes fakes with the same shape: thousands of small generated functions, a setup that runs some of them, and the requests a real script makes. It’s long and you don’t change it, so take it from the course repository. Run it once:
node third-party/make-fakes.js
It writes analytics.js (267,080 bytes), payment.js (367,393 bytes) and analytics-config.json. Here’s the end of the new analytics.js, after 1,600 generated functions:
// Excerpt from third-party/analytics.js, written by make-fakes.js.
var steps=[_f63h0,_28aq21,_z62lo2 /* ... 500 functions */];
// Setup at load: runs the used functions, as a real script's setup would.
var seed=0;for(var r=0;r<40;r++)for(var j=0;j<steps.length;j++)seed=steps[j](seed,r)|0;
// Records every tap for the heatmap.
addEventListener('pointerdown',function(e){var t=performance.now();while(performance.now()-t<2);},{capture:true,passive:true});
// Loads its settings from its own server, then sends the page view there.
fetch('http://127.0.0.1:8081/analytics-config.json').then(function(r){return r.json()}).then(function(c){
navigator.sendBeacon('http://127.0.0.1:8081/collect',JSON.stringify({page:location.pathname,site:c.site}));
});
payment.js has 2,200 functions and runs 700 of them at load. It also sends a beacon of fraud signals and listens to pointermove. A page shows the payment widget with Pay.mount(box, { amount }).
Tuesday’s three changes
Nina added one line to the <head> of show.html, seats.html and checkout.html, below the analytics script:
<script src="http://127.0.0.1:8081/payment.js" async></script>
On checkout.html she removed the old payment.js line at the end of the <body>. public/checkout.js now mounts the widget, in place of its last line:
// The payment script loads with async. Once it has run, it draws its widget in the box.
addEventListener('load', () => Pay.mount(document.getElementById('payment'), { amount: total }));
An async script delays the load event, so Pay exists when the listener runs.
Omar’s button finds the best block of free seats side by side. He used three helpers from lodash, a utility library, and copied its minified build into public/vendor/lodash.min.js (73,234 bytes, from lodash 4.18.1). In seats.html, he added the button below the status line and the library above seats.js:
<p><button id="best" type="button">Find the best 2 seats</button></p>
<script src="/vendor/lodash.min.js"></script>
<script src="/seats.js"></script>
And in public/seats.js, above render();:
// Finds the best block of free seats side by side: the row nearest the stage, then the middle.
function bestSeats(count) {
const blocks = _.chunk(seats, 200).flatMap((row) =>
_.range(0, 200 - count + 1).map((start) => row.slice(start, start + count)));
const free = blocks.filter((block) => block.every((seat) => !seat.sold && !picked.has(seat.id)));
return _.minBy(free, (block) => block[0].row * 1000 + Math.abs(block[0].number + (count - 1) / 2 - 100.5));
}
document.getElementById('best').addEventListener('click', function pickBest() {
const block = bestSeats(2);
if (!block) return;
elements[block[0].id].scrollIntoView({ block: 'nearest' });
for (const seat of block) {
picked.add(seat.id);
renderSeat(seat);
}
renderSummary();
});
The handler scrolls to the seats before it changes them, so the scroll doesn’t force a layout (Module 6).
The release on the phone profile
The runs behind this module used headless Chrome 157 on the 2019 laptop (Intel Core i7-9750H), driven through the DevTools Protocol, as in Modules 1 to 6. The phone profile is Module 1’s: 412 × 823, device pixel ratio 1, touch, Slow 4G and 6x CPU, with the cache disabled. Each version ran three times unless a line says otherwise. Your numbers will differ.
In three loads of the show page, FCP and LCP were both 2,004–2,036 ms, against 1,320–1,352 ms before the release. Two long tasks appeared: 218–240 ms at about 1.67 s, and 285–290 ms at about 2.46 s. Long animation frames named their scripts: analytics.js and payment.js. TBT, counted from FCP as Lighthouse counts it, was 235–240 ms, against 0 ms.
Figure 1 is one of those loads on the page-load timeline, at 100 ms per character as in Module 3.
time (s) 0 1 2 3 4
| | | | |
show.html ======
styles.css ======
show.css ======
analytics.js =========== sync, NEW version
payment.js ================== async, NEW
show.js ================ defer
stadium-400 ========
main thread [a] [p]
^ TTFB 0.57 s
^ FCP and LCP 2.00 s
a = analytics.js runs, 224 ms; p = payment.js runs, 285 ms
Figure 1: the picture is ready at 1.37 s, but the first paint waits for analytics.js to download and run.
Answer to the prediction
Both cost the page, in different ways. analytics.js blocks the parser, so its download, about 1.05 s on Slow 4G, delays the first paint directly; its run adds about 220 ms more. payment.js is async, so its 1.8 s download blocks nothing. But its run is a 285 ms task at 2.46 s, when a quick buyer taps Buy.
The laptop alone showed none of it. Without throttling, three loads had FCP at 104–116 ms and at most one task over 50 ms, of 51 ms. The files arrived at once over the local network, and the CPU ran both scripts six times faster. But on a phone, both costs grow, and a 285 ms task lands inside the first seconds after the button appears.
What a script costs after its last byte
Module 3 showed when a script blocks the parser or the first paint. This section follows the bytes after they arrive: what V8, Chrome’s JavaScript engine, does with them, and which part runs on the main thread.
Download, parse, compile and run
A script costs four steps: download, parse, compile and run. V8 parses the source, compiles it to bytecode for its interpreter, and then runs the top-level code (V8 blog, 2019). The network sees the compressed bytes, but V8 parses the uncompressed ones: 267 KB for analytics.js, not 66 KB.
Streaming compilation is V8 parsing and compiling a script on a background thread while its bytes still arrive. V8 starts once it’s seen at least 30 KB. Chrome did this first for async and defer scripts, and since Chrome 72 (2019) for parser-blocking scripts too. The compile then ends a few milliseconds after the last byte (same post).
But the background thread doesn’t compile every function. Lazy parsing is V8 skipping the body of a function it doesn’t expect to run yet: it checks the syntax, notes the variables, and moves on (V8 blog, preparser). The top-level code, and functions wrapped in parentheses as if called at once, are compiled up front.
A lazily parsed function is compiled when it is first called. That compile runs on the main thread, and the script waits for it (V8 blog, explicit compile hints, 2025). Then the main thread runs the top-level code as one task, and every function the setup calls for the first time is compiled inside that task.
Figure 2 shows where each step runs.
network [======== bytes arrive ========]
background [parse + compile top-level code, as bytes arrive]
thread
main thread [run top-level code ]
[c][c] [c][c][c] [c]
c = compile one function
on its first call
Figure 2: streaming moves the first compile off the main thread; the first call of each lazy function, and the run, stay on it.
V8 has faster compilers above the interpreter: Sparkplug since Chrome 91 (2021), Maglev since Chrome 117 (2023), and TurboFan at the top (V8 blog, Maglev). They compile code that runs often. But a page load runs most of its code once, so its cost is the parse, the first compile and the run.
Rule: The network pays for compressed bytes; the main thread pays for every function the page calls and for the run itself.
When the browser runs a script
Where a script tag sits, and its attributes, decide when the run happens. Module 3 taught parser-blocking and render-blocking; Figure 3 adds when each kind runs (MDN, <script>).
| Script | Download | Run | Blocks the parser |
|---|---|---|---|
| Classic, no attribute | at once | as soon as it arrives | yes, until it has run |
async |
in parallel | as soon as it arrives, in any order | only while it runs |
defer |
in parallel | after parsing, in document order, before DOMContentLoaded |
no |
type="module" |
in parallel; its imports once it has arrived | like defer, unless it is async |
no |
| Added by a script | when added | as soon as it arrives, like async |
no |
Figure 3: no attribute removes the run; it only moves it.
async doesn’t make a script free. Its download blocks nothing, but its run is one main-thread task at the moment it arrives. On the show page, that moment was 2.46 s, half a second after the button appeared.
The second visit: the code cache
V8 can skip most of the parse and compile next time. The code cache is compiled code that V8 stores next to a script in the HTTP cache, to reuse when the file runs again (V8 blog, code caching for developers, 2019, updated 2020).
The first run compiles only. On a later run, V8 compiles again and stores the result, including the functions that ran during the first execution. After that, a run can load the stored code instead of compiling.
The V8 team said in 2019 that this needs two visits within 72 hours. But the current post gives no window and says the rules change often.
The code cache has three limits that matter here:
- Per file. Any change to the file makes its cached code useless. So a new release of a third party starts over on every buyer’s phone.
- Per site. The HTTP cache is partitioned by site (Module 4). A third party’s file, and the code stored with it, is cached once for each site that loads it.
- Small scripts. V8 doesn’t cache scripts under 1 KB.
In a trace, the details of a Compile script event show the cache state: loaded from the cache, rejected, or not eligible (DevTools source, TimelineUIUtils.ts). The runs in this module disable the cache, so every load is a first visit.
What makes a script a third party
The Performance panel groups every request and every task by the company or site it belongs to. For a known domain, it uses the open Third Party Web dataset. For any other domain, it uses the root domain and ignores the port (third parties insight, 2025). That’s why the fakes come from 127.0.0.1: localhost on another port would count as TinyTickets (Module 1).
A third-party script is code you can’t change. Its size, its setup and the requests it makes are the provider’s choice. Yours is whether it loads on a page, when it loads, and where it runs.
Find the cause in the trace
Module 2 read a slow tap’s trace. Here you’ll read a load, and sort its work by who wrote the code.
-
Record the load. Set the phone profile, open the show page, and click Record and reload in the Performance panel. On the Main track, two long tasks stand out after the first second. Each one is an Evaluate script event.
-
Sort the work by party. With nothing selected, the Summary tab lists the time per party: the first party,
localhost, and each third party, here127.0.0.1. Check Dim 3rd parties to gray out every event that isn’t TinyTickets’. Both long tasks turn gray.
Since Chrome 134 (2025), the table also links to Bottom-up, grouped by party (What’s new in DevTools 134).
- Open one long task. Figure 4 draws the
analytics.jstask from one recorded run as a simplified flame chart, at 20 ms per character. Recording with V8’s compile categories slows the page, so this task took 332 ms, against 218–240 ms without the recording.
time (ms) 0 200 400
| | |
Task [===============]
Evaluate [ analytics.js ]
script
Compile code ' '' ' ''' '' ' 500 events, 54 ms in all
Figure 4: one task runs the whole setup; each ' stands for a burst of lazy compiles inside it.
- Read the compile. Above the task, a Compile script event of 0.1 ms has the detail Streamed: true. The parse happened on a background thread, in a streaming task of 438 ms while the bytes arrived. Only about 14 ms of it was parsing; the rest was waiting for the network.
On the main thread, inside Evaluate script, 500 Compile code events compiled the 500 functions the setup calls. payment.js looked the same: a 425 ms task with 700 Compile code events, 62 ms in all.
Pause and predict. Lazy compiles were 54 ms of a 332 ms task. Suppose V8 compiled every function of analytics.js up front, on the background thread. How much shorter would the task get, and what would it cost?
Answer
At most about 54 ms shorter, the compiles of the functions the setup calls; the other 1,100 functions never run, so compiling them would be wasted work and memory. Most of the task, about 280 ms, is running the setup itself. Chrome 136 (2025) added a way to ask for this per file, a //# allFunctionsCalledOnLoad comment at its top, and the V8 team says to use it sparingly (V8 blog). But only the provider can add it to its own file.
- Measure each third party alone. To see one script’s cost on its own, remove it and load again. In DevTools, right-click the request in the Network panel and choose Block request URL.
The blocked URLs are listed in the Request conditions drawer, the name the Network request blocking drawer got in Chrome 144 (2026) (Request conditions). Figure 5 has three loads each.
| Show page | FCP | LCP | Long tasks after 1 s | TBT |
|---|---|---|---|---|
| Tuesday’s release | 2,004–2,036 ms | 2,004–2,036 ms | analytics.js 218–240 ms, payment.js 285–290 ms |
235–240 ms |
analytics.js blocked |
1,304–1,336 ms | 1,324–1,348 ms | payment.js 296–374 ms |
246–324 ms |
payment.js blocked |
1,992–2,004 ms | 1,992–2,004 ms | analytics.js 219–227 ms |
0 ms |
Figure 5: the analytics script costs the first paint; the payment script costs the time after it.
TBT is 0 ms with payment.js blocked, although analytics.js still runs for about 220 ms. That’s because TBT starts at FCP, and that task ends before the first paint. It blocks the paint instead, which FCP shows.
Blocking is a lab tool only, because a blocked analytics script also stops sending page views, and a blocked payment script breaks checkout.
- Find code that did not run. The Coverage panel is a DevTools panel that records which bytes of each script and stylesheet ran while it recorded. Open it from the Command Menu with Show Coverage, choose Per block, and reload (Coverage). It keeps recording while you use the page.
Figure 6 has one load of the seat map from Tuesday’s release, recorded with block coverage through the protocol. Its last column is the same load after one tap on Find the best 2 seats.
| Script on the seat map | Size | Unused after the load | Unused after one Best tap |
|---|---|---|---|
analytics.js (third party) |
267,083 B | 67.0% | 67.0% |
payment.js (third party) |
367,400 B | 66.5% | 66.5% |
vendor/lodash.min.js |
73,234 B | 73.3% | 71.9% |
seats.js |
3,299 B | 30.9% | 12.3% |
Figure 6: two thirds of each third-party script never ran, and neither did almost three quarters of the library behind one button.
“Unused” means “didn’t run while the panel recorded”, not “never needed”. The Best button’s code in seats.js was unused until the tap. Code for errors, for other pages and for other browsers shows as unused too.
But the lodash row tells Maya something the third-party rows can’t. The tap ran about 1 KB more of the library. The other 52 KB of it is parsed on every load and never runs, and it’s TinyTickets’ own file, so she can remove it. The panel can’t record a page that came from the back/forward cache or a prerender, so reload it in a normal tab.
Rule: Measure a third party by removing it, and your own code by what runs.
The fixes, one change at a time
Every number below comes from the phone profile in headless Chrome 157, three loads each, unless a line says otherwise.
Fix 1: the payment script only where buyers pay
The provider’s integration guide asks for two things. Load the script from the provider’s own servers, never from a copy or a bundle, so that its security fixes reach every site at once. And load it on every page, because its fraud checks learn from what a buyer does before checkout. Check your own provider’s guide, because the rules differ between providers.
The first rule leaves Maya one choice, which is where the script loads. So Maya asked the provider what it loses when the script runs only on checkout. The answer was that checkout-only works, but its fraud checks see less. Leo accepted that for the show pages and the seat map.
Remove this line from show.html and seats.html, and keep it in checkout.html:
<script src="http://127.0.0.1:8081/payment.js" async></script>
On the show page, the 285–290 ms task after the first paint was gone, and TBT fell from 235–240 ms to 0 ms. FCP stayed at 1,984–1,996 ms, because analytics.js still blocks it. On the seat map, a 287–288 ms task at about 4.6 s was gone. On checkout nothing changed, by design: payment.js still ran for 287–292 ms.
Figure 7 shows which page now loads which third party, after both fixes in this part.
(Buyer) --> [show page] ---> [analytics script] after load, Fix 2
--> [seat map] ---> [analytics script] after load, Fix 2
--> [checkout] ---> [analytics script] after load, Fix 2
---> [payment provider's script] only here, Fix 1
Figure 7: the payment script moves to the one page that needs it; the analytics script stays everywhere, but later.
The costs of Fix 1:
- The fraud checks see less. The provider gets no signals from the show page and the seat map. If fraud grows, that’s the first thing to undo.
- Checkout pays the full price. A buyer who reaches checkout waits for the download and the 290 ms run there, at the moment they want to pay. A
preconnectfrom the seat map wouldn’t help. Chrome closes a connection that isn’t used within 10 seconds, and buyers spend longer than that on the map (web.dev).
Other ways to contain a third party
Loading a script on fewer pages is one way. web.dev lists the others, and three matter here (web.dev, third-party JavaScript):
- Later on the same page. Keep the payment script on every page, but load it after the page has loaded, with Fix 2’s loader. The provider keeps its signals, but every page still runs a 290 ms task, later.
- A facade. A facade is a static element that looks like a third-party embed and loads the real one only when the user interacts with it. Lighthouse’s old audit gave a video player example: a 3 KB facade in front of a 540 KB player (Lighthouse docs). It fits a chat button or a video. But it doesn’t fit the Pay button: the buyer’s tap would wait for 1.8 s of download and 0.3 s of setup on the phone profile.
- An iframe. A third party from another site, inside an
<iframe>, gets its own document and globals, so its code can’t touch the page’s DOM. Whether a cross-site frame also gets its own main thread depends on site isolation, which varies by platform.
Two more are out for this script. Self-hosting a copy breaks the provider’s first rule, and it saves only a connection: the main-thread work stays the same, and DevTools stops calling it a third party. Running it in a web worker breaks a widget that draws in the page.
Fix 2: the analytics script after the page has loaded
The analytics script has no rule about where it loads, and Leo wants it on every page. So the question is when. Figure 8 compares four ways, each measured on the show page after Fix 1.
analytics.js loaded |
FCP | LCP | Its 220 ms task runs at | TBT |
|---|---|---|---|---|
In <head>, no attribute (after Fix 1) |
1,984–1,996 ms | 1,984–1,996 ms | about 1.67 s, before the first paint | 0 ms |
async |
1,304–1,320 ms | 1,388–1,396 ms | about 1.69 s | 169–173 ms |
defer |
1,296–1,308 ms | 1,392–1,404 ms | about 1.69 s | 167–173 ms |
After load, when idle |
1,296–1,308 ms | 1,328–1,340 ms | about 2.9 s | 156–164 ms |
Figure 8: three ways give the first paint back; none of them removes the task.
Pause and predict. With async and defer, nothing waits for analytics.js before the first paint. Why is LCP still about 60 ms later than with the script loaded after load?
Answer
Bandwidth. With async or defer, the 66 KB of analytics.js downloads at the same time as the picture, over the same Slow 4G link, so the picture arrives later. But loaded after load, the script starts downloading at 1.95 s, when the picture is already on screen.
async and defer behave the same here, because the show page has nothing else to run. Both put the 220 ms task 0.4 s after the Buy button appears, when a quick buyer taps it. In the last three rows TBT barely changes, because the work is the same; only its time moves.
TinyTickets loads the script after load, for two reasons. First, the download no longer competes with the picture. And a loader can wait until a prerendered page is shown, which Module 4 left to this module. In Module 4’s prerender, the old tag ran 9 s before the buyer saw the page.
Create public/load-analytics.js:
// Loads the analytics script after the page's load event, when the main thread is idle.
// A prerendered page waits until the buyer sees it (Module 4).
function loadAnalytics() {
const script = document.createElement('script');
script.src = 'http://127.0.0.1:8081/analytics.js';
document.head.append(script);
}
function whenIdle() {
// Safari has no requestIdleCallback; a timer after the load event is the fallback.
if (window.requestIdleCallback) requestIdleCallback(loadAnalytics, { timeout: 2000 });
else setTimeout(loadAnalytics, 500);
}
function afterLoad() {
if (document.readyState === 'complete') whenIdle();
else addEventListener('load', whenIdle, { once: true });
}
if (document.prerendering) document.addEventListener('prerenderingchange', afterLoad, { once: true });
else afterLoad();
In show.html, seats.html and checkout.html, replace the analytics tag with the loader:
<script src="/load-analytics.js" defer></script>
requestIdleCallback() runs its callback when the browser has no other work for the rest of a frame, or after timeout ms at the latest (MDN). But the idle wait only decides when the request starts. A script added by a script runs like async, as one task when it arrives.
Figure 9 is the show page after Fixes 1 and 2, from one run.
time (s) 0 1 2 3 4
| | | | |
show.html ======
styles.css ======
show.css ======
loader ====== NEW, defer
show.js ====== defer
stadium-400 =======
analytics.js ========= NEW: requested after load
main thread [a]
^ FCP 1.31 s, LCP 1.34 s
^ load 1.93 s
loader = load-analytics.js; a = analytics.js runs, 209 ms
Figure 9: the first paint is back at Module 6’s time, and the analytics task runs a second after the load.
FCP was 1,296–1,308 ms and LCP 1,328–1,340 ms, the same as before Tuesday’s release. The payment task is gone, and the analytics task ran at about 2.9 s.
The costs of Fix 2:
- Page views are lost. In the lab, the page view left the browser at about 3.7 s. So a buyer who closes the tab before that is never counted, and the heatmap misses taps made before the script ran.
- The task still runs. A buyer who taps at about 2.9 s waits up to 220 ms. Fix 2 moves the work to a quieter moment; it doesn’t remove it.
- One more small file. The loader is a fourth request on every page. Fix 3 folds it into a bundle.
The choice flips with what the script does. A script that must see the first second, such as an A/B test that changes the page, can’t wait for load, so it needs async and a small size. But a script that only reports can wait even longer, until the first tap or until the page is hidden.
A web worker is the remaining place to move it. Partytown runs third-party scripts in a worker and passes their DOM calls to the main thread; version 1.0 shipped in October 2026 (releases).
Its own docs list the costs (trade-offs). DOM access from the worker is deliberately slow, and preventDefault() in a third party’s handler has no effect. Scripts served without CORS headers need a proxy. So it can fit an analytics script, but it doesn’t fit a payment widget.
Fix 3: a bundler for TinyTickets’ own code
The third parties are contained. But TinyTickets’ own JavaScript has three problems a bundler can solve. The seat map parses 73 KB of lodash for one button. Every page loads vitals.js, which then requests its library, a chain Module 3 left on purpose.
And the file names never change, so Module 4 couldn’t cache them for long.
A bundler reads a page’s entry file, follows its import statements, and writes the code into a few output files. This lab uses esbuild 0.28.2 (August 2026), because one call does everything below, with no config file (esbuild API). Webpack, Rollup and Rolldown do the same jobs.
Install it, with lodash from npm instead of the copied file:
npm install --save-dev --save-exact esbuild@0.28.2 lodash@4.18.1
npm pkg set scripts.build="node build.js" scripts.start="node build.js && node server.js"
Move show.js, seats.js, checkout.js, vitals.js and load-analytics.js from public/ to a new src/ folder, and delete public/vendor/. Each page’s script now imports what it needs. At the top of src/show.js, src/seats.js and src/checkout.js, add:
import './vitals.js';
import './load-analytics.js';
src/seats.js also imports the three helpers, and calls them without the _.:
import { chunk, minBy, range } from 'lodash';
In src/vitals.js, import the library by its package name, the web-vitals dependency the lab has had since Module 1:
import { onCLS, onINP, onLCP } from 'web-vitals/attribution';
Each page now has one script tag. In show.html, replace the tags for load-analytics.js, show.js and vitals.js with one line; in seats.html and checkout.html, do the same for their own files and the lodash copy:
<script type="module" src="/assets/show.js"></script>
Create build.js in the lab folder:
// Bundles each page's script into public/assets/ with a hash of its content in the file name,
// then points each page at its new files. Run it from the lab folder: node build.js
import * as esbuild from 'esbuild';
import { readFile, rm, writeFile } from 'node:fs/promises';
const pages = ['show', 'seats', 'checkout'];
await rm('public/assets', { recursive: true, force: true });
const result = await esbuild.build({
entryPoints: pages.map((page) => `src/${page}.js`),
bundle: true,
minify: true,
format: 'esm',
splitting: true,
outdir: 'public/assets',
entryNames: '[name]-[hash]',
chunkNames: 'chunk-[hash]',
metafile: true,
});
await writeFile('meta.json', JSON.stringify(result.metafile));
console.log(await esbuild.analyzeMetafile(result.metafile));
for (const [file, output] of Object.entries(result.metafile.outputs)) {
const page = output.entryPoint?.slice('src/'.length, -'.js'.length);
if (!pages.includes(page)) continue; // a shared chunk, or a file loaded with import()
// The chunks the page imports at once: name them in the HTML, so they do not wait for the entry file.
const preloads = output.imports
.filter((i) => i.kind === 'import-statement')
.map((i) => `<link rel="modulepreload" href="${i.path.slice('public'.length)}">\n `)
.join('');
const html = (await readFile(`public/${page}.html`, 'utf8'))
.replace(/ *<link rel="modulepreload" href="\/assets\/[^"]+">\n/g, '')
.replace(new RegExp(`<script type="module" src="/assets/${page}(-\\w+)?\\.js">`),
`${preloads}<script type="module" src="${file.slice('public'.length)}">`);
await writeFile(`public/${page}.html`, html);
}
The options do three jobs:
- Bundle and measure.
bundlefollows the imports, andminifyshortens the code.metafilerecords which input files ended up in which output file and how many bytes each one adds.analyzeMetafile()prints that record as a tree. - Share. Code splitting is a bundler writing a page’s code into several files that load separately, instead of one file per page. With
splitting, code that two or more pages import goes into a chunk, an output file that is not an entry of its own. esbuild splits only withformat: 'esm', and its docs still call splitting a work in progress. - Name by content.
[hash]puts a hash of the file’s content in its name: Module 4’s versioned URL. The loop then writes the new names into each page.
Run npm run build. It printed:
public/assets/seats-LRTGTRTZ.js 73.2kb 100.0%
├ node_modules/lodash/lodash.js 71.1kb 97.1%
└ src/seats.js 1.7kb 2.3%
public/assets/chunk-BPROS4KU.js 14.7kb 100.0%
├ node_modules/web-vitals/dist/web-vitals.attribution.js 13.1kb 89.5%
├ src/vitals.js 584b 3.9%
└ src/load-analytics.js 396b 2.6%
public/assets/checkout-7C2K7ORY.js 338b 100.0%
└ src/checkout.js 309b 91.4%
public/assets/show-6R6XEX33.js 250b 100.0%
└ src/show.js 221b 88.4%
Lodash is 97.1% of the seat map’s file. The three pages share one chunk with vitals.js, the loader and web-vitals. The hashes in your names will differ, because they depend on every input byte.
The chain inside a bundle
A module script’s imports are a chain. The browser learns that seats-LRTGTRTZ.js imports the chunk only once that file has arrived. So a first build without the preloads lines requested the chunk about 0.6 s later, one Slow 4G round trip. The seat map’s script then started at 2.04–2.05 s instead of about 1.5 s.
modulepreload is a <link rel="modulepreload"> that fetches a module script, parses and compiles it, and stores it for the page before any script imports it (MDN). The preloads lines in build.js write one for each chunk the page imports at once, from the metafile’s imports. After a build, seats.html has:
<link rel="modulepreload" href="/assets/chunk-BPROS4KU.js">
<script type="module" src="/assets/seats-LRTGTRTZ.js"></script>
Use modulepreload, not preload, for a module: a preload without the right crossorigin value downloads a copy the module loader cannot use (web.dev).
Cache the hashed files for a year
A hashed file never changes under its name, so you can cache it for a year without a check. In server.js, replace cacheControl():
// Pictures and the bundler's hashed files never change under the same name.
// Every other file is checked with its ETag on each use.
function cacheControl(path) {
const forever = ['.jpg', '.avif'].includes(extname(path)) || path.includes(join('public', 'assets'));
return forever ? 'max-age=31536000, immutable' : 'no-cache';
}
The HTML keeps no-cache. It’s the one file that must change for a buyer to get new code, because it names the new hashes.
The costs of Fix 3:
- A build step. The pages now work only after
npm run build. So a deploy that skips it serves HTML that names files which don’t exist. - Minified code in traces. The flame chart shows short minified names, such as
aorVe. But esbuild can write source maps with itssourcemapoption, so that DevTools can map the code back tosrc/. - Hashes change with any input. An update of
web-vitalsgives the shared chunk a new name, and every buyer downloads it again on the next visit. - Splitting is young in esbuild. Its docs list a known problem with the order of
importstatements across chunks. Webpack and Rollup have split code for longer.
The choice flips with the size of the code. If you have one page with one small script, a bundler adds a build step for little. But here it removes a request chain, gives every file a long cache life, and measures what each page ships.
What Fix 3 changed, and what it did not
The seat map now requests two script files at once, its entry and the shared chunk. Before, it requested the lodash copy, seats.js, vitals.js, the loader, and the web-vitals file that vitals.js imported. Module 3’s chain is gone: with the preload, the chunk started at about 0.62 s, where the web-vitals file had started at about 1.3 s.
But the bytes didn’t shrink yet. The seat map’s file is 27,552 bytes over the network and 74,983 to parse, about what the lodash copy and seats.js were. In separate runs, its script ran 918–952 ms in the long frame, against 833–856 ms for the two files before: 32–34 ms of lodash and 801–822 ms of seats.js. esbuild wraps a CommonJS package in a function that runs on its first import, but these runs don’t show why that took about 100 ms more.
Don’t read the seat map’s LCP for these fixes. LCP measures the picture, and the picture paints either before the 1.9 s long frame or after it, depending on when the script starts. In this module’s runs it was 1.3–1.4 s whenever something delayed the script, such as the blocking lodash copy, and 3.5–4.5 s otherwise. The end of the long frame, when the map appears, stayed between about 3.2 and 3.9 s in every version.
Fix 4: tree shaking, and a library that allows it
seats.js calls three lodash functions, but the bundle kept all 71 KB. Tree shaking is a bundler leaving out the code that no import can reach from an entry file. It relies on the static structure of ES modules: their import and export lines are fixed before any code runs, so the bundler can follow them (webpack, tree shaking).
The lodash package is CommonJS. Its exports are properties that its code sets while it runs, so a bundler can’t tell which parts chunk, minBy and range need, and keeps the whole file. But the same functions ship as ES modules in lodash-es, one file per function.
A bundler also needs to know that skipping a file is safe. sideEffects is a package.json field that tells bundlers which files of a package do something when they are imported, beyond defining exports. "sideEffects": false, which lodash-es sets, says that no file does, so a file whose exports nothing uses can be left out whole (esbuild API).
Swap the package:
npm uninstall lodash && npm install --save-dev --save-exact lodash-es@4.18.1
In src/seats.js, change the import:
import { chunk, minBy, range } from 'lodash-es';
Pause and predict. chunk and range are a few lines each, and minBy is a loop. How large will the lodash part of the seat map’s file be now?
Answer
About 17.6 KB. npm run build printed public/assets/seats-EFZJ54PC.js at 19.2kb, with src/seats.js 1.6kb and 129 small lodash-es files for the rest. Bundling the functions alone showed where it comes from: chunk and range together made 3.4kb, and minBy alone 16.0kb.
minBy accepts a function, a property name such as 'price', or an object pattern as its second argument. The code that handles the last two, including a deep equality check, comes with it, used or not. Tree shaking removes what no import reaches, not what your call happens not to use.
The seat map’s own JavaScript went from 27,552 to 7,909 bytes over the network, and from 74,983 to 19,688 bytes to parse. In three loads each, the script in the seat map’s long frame ran 830–847 ms, against 918–952 ms with all of lodash. The first Best tap still showed its seats after 82–93 ms.
The costs of Fix 4:
- It depends on the package. Tree shaking needs ES modules all the way down. So one CommonJS dependency deep inside a package brings its whole file.
sideEffectsmust be true to the code. esbuild’s docs call the field error-prone. A new file with a side effect, missed in the field, breaks the package for anyone who bundles it. In a test package marked"sideEffects": false, animport 'seat-widgets/register.js'that defines a custom element was dropped, and esbuild 0.28.2 printed:
▲ [WARNING] Ignoring this import because
"node_modules/seat-widgets/register.js" was marked as having no side effects
[ignored-bare-import]
The warning is one line in the terminal; it’s wrapped here.
The warning names the import, so read build warnings before you ship.
A third way removes the library: three helpers in plain JavaScript are about ten lines, and add nothing to the bundle. The choice flips with how much of a library a page uses. If a page uses three small functions, write them. If it uses a dozen, an ES-module package with tree shaking keeps the code you’d otherwise write and test yourself.
Fix 5: load the Best seats code on the first tap
What’s left of lodash runs only when a buyer taps Find the best 2 seats. So code splitting can move it out of the load. Dynamic import() is an expression that loads a module when the code reaches it, and returns a promise of the module’s exports (MDN). With splitting on, esbuild writes the imported module, and the code only it uses, into a chunk of its own.
Move the search into src/best-seats.js, with the seats and the picked set as arguments:
import { chunk, minBy, range } from 'lodash-es';
// Finds the best block of free seats side by side: the row nearest the stage, then the middle.
export function bestSeats(seats, picked, count) {
const blocks = chunk(seats, 200).flatMap((row) =>
range(0, 200 - count + 1).map((start) => row.slice(start, start + count)));
const free = blocks.filter((block) => block.every((seat) => !seat.sold && !picked.has(seat.id)));
return minBy(free, (block) => block[0].row * 1000 + Math.abs(block[0].number + (count - 1) / 2 - 100.5));
}
In src/seats.js, delete bestSeats() and the lodash import, and load the file in the handler:
document.getElementById('best').addEventListener('click', async function pickBest() {
// The code that finds the seats is a separate file, loaded on the first tap.
const { bestSeats } = await import('./best-seats.js');
const block = bestSeats(seats, picked, 2);
if (!block) return;
elements[block[0].id].scrollIntoView({ block: 'nearest' });
for (const seat of block) {
picked.add(seat.id);
renderSeat(seat);
}
renderSummary();
});
npm run build now writes the seat map’s entry at 1.6kb and a new chunk of 17.8kb with src/best-seats.js and the 129 lodash-es files. The chunk isn’t in seats.html: the browser requests it on the first tap.
Pause and predict. The first tap now waits for a 7 KB download on Slow 4G. Will that tap’s INP get longer or shorter?
Answer
Shorter, but the buyer waits longer. In three loads, the first tap’s Event Timing entry fell from 160–176 ms to 48–56 ms. But the picked seats appeared 701–712 ms after the tap, against 82–93 ms before.
The handler stops at await import(), so the browser paints a frame at once; Event Timing ends there. But the seats change one round trip later, in a task that no interaction is linked to. The second tap took 24–32 ms, and its seats appeared after 78–84 ms, because the chunk was then loaded.
INP didn’t see the wait, so a field report wouldn’t have either. But a buyer saw a button that did nothing for 0.7 s.
TinyTickets keeps the split and hides the wait. Once the page is idle after load, it loads the chunk in advance. Add at the end of src/seats.js:
// Loads the Best seats file once the page is idle, so the first tap rarely waits for the network.
addEventListener('load', () => (window.requestIdleCallback ?? setTimeout)(() => import('./best-seats.js')));
A second import() of a module that has already loaded resolves at once, from the page’s module map. In three loads, the chunk arrived 4.4–5.5 s after the start, and the first tap’s seats appeared after 96–178 ms. But a buyer who taps before the chunk arrives still waits.
The costs of Fix 5:
- A round trip on first use. Anything loaded with
import()adds the network to the interaction. MDN advises using dynamic import only when necessary, and web.dev notes that smaller split files add round trips on a first visit (web.dev, code splitting). - Metrics that miss the wait. The tap’s INP improved while the result came later. You’ll want to measure the time to the result, with a mark when the seats change, not only INP.
- More files to cache and to version. Each chunk is one more request and one more name in the build.
- The warm-up downloads for everyone. Buyers who never tap the button still fetch the 7 KB, after the load.
The choice flips with size and use. A chunk of hundreds of kilobytes that one buyer in twenty uses, such as a seat view in 3D, belongs behind import().
But for a 7 KB chunk that every second buyer taps, the split saves little. Without the warm-up it costs a round trip, and with it the chunk downloads on almost every visit anyway. TinyTickets keeps it, because the load parses 18 KB less, and will decide again if the button stays this small.
Fix 6: the seat map’s own 0.8 s
Module 6 handed over one more cost: about 0.8 s of script in the seat map’s first long frame. None of the fixes above touched it. Coverage shows why: the part of seats.js that didn’t run at load is its handlers, about 1 KB, and the slow part ran because the map needs it. The cost isn’t the parse or the compile either, because the file is 1.6 KB.
The Bottom-up tab of a load trace names it, as in Module 2. render(), about 630 ms, writes a class, a title and three ARIA attributes to each of 60,000 seats. build-map created those seats empty a moment before. That’s two passes over every seat: one to create it, one to describe it.
One pass is enough, so build each seat’s markup with its state and label in the string, and drop render() from the load. In src/seats.js, replace the lines from const buildStart to the build-map measure:
// The markup for one seat, with the same state and label renderSeat() gives it.
function seatHTML(seat) {
const state = seat.sold ? 'sold' : 'free';
const label = `Row ${seat.row}, seat ${seat.number}, $${seat.price}, ${state}`;
return `<span class="seat ${state}" title="${label}" aria-label="${label}" aria-disabled="${seat.sold}" aria-pressed="false"></span>`;
}
const buildStart = performance.now();
// One element per stadium row, written once with every seat's state: no second pass over 60,000 seats.
let html = '';
for (let i = 0; i < SEAT_COUNT; i += 200) html += `<div class="row">${seats.slice(i, i + 200).map(seatHTML).join('')}</div>`;
map.innerHTML = html;
const elements = [...map.querySelectorAll('.seat')];
performance.measure('build-map', { start: buildStart });
Delete render(), and call renderSummary() where render() was called. renderSeat() stays for taps and the pageshow refresh.
Measured on Module 6’s code, three loads each, the script in the seat map’s long frame went from 793–818 ms to 639–648 ms. LCP went from 3,632–3,712 ms to 3,496–3,528 ms. build-map grew from about 140 ms to 577–595 ms, because the parser now creates the attributes, but render()‘s 613–633 ms is gone. With every fix of this module, the script ran 648–681 ms.
The costs of Fix 6:
- A 9 MB string. The markup is 9,042,900 characters before the parser turns it into elements. It’s garbage soon after, but a phone short of memory feels it, and Module 8 is about memory.
- Two places describe a seat.
seatHTML()andrenderSeat()must agree on the class and the label. So a change to one and not the other shows a seat differently after its first tap. - Text in HTML must be escaped. The labels here are numbers and fixed words. But a label built from an organizer’s text would need escaping before it goes into
innerHTML.
The rest of the long frame is style, layout and paint for 60,000 elements, which Module 6 kept when it chose the DOM over a canvas.
The second visit, with hashed names
Fix 3 gave the bundled files a year in the cache, as Module 4 wanted. A second-visit test loaded a page, waited 10 s, opened a blank page, and loaded it again, with the cache on and a fresh browser profile each time.
Pause and predict. In Module 4, a variant that cached every file but the HTML moved the seat map’s FCP to 3.4 s. The cached seats.js ran before the first paint. Will that happen again with the bundled seat map?
Answer
Not in these runs. Figure 10 has three runs each.
| Second visit | Responses | Over the network | FCP |
|---|---|---|---|
| Seat map, after Fix 2 | 11 | 10 | 1,304–1,368 ms |
| Seat map, the saved lab | 9 | 5: the HTML, styles.css and the analytics script’s three requests |
1,324–1,364 ms |
| Show page, after Fix 2 | 11 | 10 | 1,292–1,336 ms |
| Show page, the saved lab | 9 | 6 | 1,292–1,324 ms |
Figure 10: the hashed files come from the cache with no request, and the first paint stays where it was.
FCP stayed at the first visit’s time. styles.css keeps no-cache, so it still needs a round trip, and the first frame didn’t wait for the cached module script. But these runs don’t show the order of the two in detail.
Before and after
Figure 11 puts the seat map’s steps side by side. Its rows come from separate runs of three loads each.
| Seat map | Its own JS at load: over the network / to parse | Script in the long frame | First Best tap: seats appear after |
|---|---|---|---|
| After Fixes 1 and 2 | 27,374 B / 76,533 B, in two files | 833–856 ms | 80–99 ms |
| Fix 3: bundled, all of lodash | 27,552 B / 74,983 B | 918–952 ms | 91 ms |
Fix 4: lodash-es |
7,909 B / 19,688 B | 830–847 ms | 82–93 ms |
Fix 5: Best seats behind import() |
877 B / 1,532 B | 813–840 ms | 701–712 ms |
| Fix 6: one pass over the seats | 916 B / 1,655 B | 648–681 ms | 702–720 ms |
| Fix 5’s warm-up (the saved lab) | 959 B / 1,760 B | 678–731 ms | 96–178 ms |
Figure 11: the bytes fell by 97% with little change in time; the one pass over the seats saved the most. The table leaves out the shared chunk, 5,639 B over the network, because it replaced vitals.js, the loader and web-vitals. The last row ran on a busier laptop, so its ranges are wider.
On the show page, Fixes 1 and 2 brought FCP from 2,004–2,036 ms back to 1,296–1,308 ms, and LCP from 2,004–2,036 ms to 1,328–1,340 ms, Module 6’s numbers. With the bundle, they were 1,300–1,332 ms and 1,348–1,368 ms. The payment task is gone from the show page and the seat map, and the analytics task runs after load.
Confirming it in the field
Maya shipped the fixes the next Monday. A week later, her endpoint had 1,310 LCP lines from phones on show pages, with a 75th percentile of 2.3 s, as before the release. INP was 140 ms at the 75th percentile, over 4,150 lines.
The payment script no longer appeared in them. The analytics script was the longest script in 230 lines, all of them taps in the seconds after load.
On checkout, the payment script still was the longest script in most slow INP lines. The cost moved to the page where buyers pay, as planned.
On the seat map, the field numbers didn’t move: the first load and INP at 150 ms stayed where Module 6 left them. The saved bytes don’t show on a page whose cost is 60,000 elements, and the one-pass change is about 150 ms of a 1.9 s frame.
“The Buy button answers on the first tap again,” Leo wrote.
In Firefox and Safari
- Streaming, lazy parsing and the code cache exist in every engine, with different rules. Everything this module says about V8’s numbers, such as 30 KB and 1 KB, is V8’s.
requestIdleCallback()works in Chrome 47 and Firefox 55. Safari has it only in its Technology Preview, so the loader falls back to a timer there.document.prerenderingand prerendering are Chrome’s (Module 4). In Firefox and Safari the property isundefined, so the loader waits forloadas usual.modulepreloadworks in Chrome 66, Firefox 115 and Safari 17. Dynamicimport()works in Chrome 63, Firefox 67 and Safari 11.1.- Coverage, the third parties insight and Dim 3rd parties are Chrome DevTools features. The Firefox Profiler (Module 2) shows the same tasks, without the grouping by party.
- The field attribution of a slow interaction to a script comes from Long Animation Frames, which only Chromium browsers report (Module 5).
The support versions come from MDN’s browser compatibility data, version 8.1.9.
What changed recently
- 2023, Chrome 117: Maglev, V8’s middle compiler, shipped (V8 blog).
- 2025-03, Chrome 134: the Performance panel’s Summary separates first-party, third-party and extension work, with Dim 3rd parties (What’s new in DevTools 134).
- 2025-04, Chrome 136: the
//# allFunctionsCalledOnLoadcompile hint (V8 blog). - 2025-10, Lighthouse 13: the third-party summary became the third parties insight, and the facade audit was removed with no replacement (release notes, moving Lighthouse to insights).
- 2026-01, Chrome 144: Network request blocking became Request conditions, which can also throttle one request; Chrome 145 turned that throttling on by default (What’s new in DevTools 144, 145).
- 2026-03, Vite 8: Vite replaced its two bundlers, esbuild for development and Rollup for builds, with one, Rolldown (Vite blog).
- 2026-10: Partytown 1.0, the first stable release, now under the
@qwik.dev/partytownpackage name (releases).
Online tools for this step
These three tools take a package name or a local file, not a page URL, so Module 1’s warning about public page tests doesn’t apply. The descriptions below were checked on 2026-11-18.
Bundlephobia. You enter an npm package name and version. It builds the package on its own servers and shows its size, minified and with gzip, and an estimated download time. It also lists its dependencies and shows badges such as “tree-shakeable” and “side-effect free”. For lodash-es 4.18.1 it showed 80.6 kB minified and 28.1 kB with gzip, and an Exports Analysis with the size of each export, such as 1.1 kB for debounce.
- Data: a build of the package alone, cached per version; not your users, and not your bundle.
- Limit: it can’t see your imports or your tree shaking, so it sizes what a package could cost, not what it costs you. Some packages fail to build there.
- When your own bundler is better: once the package is installed.
analyzeMetafile()shows the bytes it adds to your files.
pkg-size.dev. You enter a package name. It runs npm install inside your browser, with StackBlitz WebContainers, and lists the install size and every dependency with its size. A second step bundles the package with esbuild-wasm to show its bundle size.
For lodash-es it showed an install size of 635 KB in one package.
- Data: a fresh install on every visit, in your browser.
- Limit: install size is what lands in
node_modules, which is mostly not what reaches buyers. The bundle step sizes the package alone, like Bundlephobia. - When your own bundler is better: for anything about your pages. Use it before you add a dependency, to see what it pulls in.
esbuild’s Bundle Size Analyzer. You open the meta.json that build.js writes. It draws each output file as a treemap, a sunburst or a flame chart. It warns when one import path resolves to more than one file in the bundle, a sign of a duplicated package.
The page’s script reads the file in your browser and doesn’t appear to upload it.
- Data: your own build, by input file.
- Limit: it shows bytes, not time; a small file can run for a long time. It needs esbuild’s metafile format. Rollup, Rolldown and Vite have their own visualizer, and webpack has webpack-bundle-analyzer.
- When DevTools is better: for what the bytes cost on a phone. Use Coverage and a trace for that, and the analyzer to find where the bytes come from.
Check yourself
Debugging scenario
Omar adds a chat button to the show pages. The chat provider’s snippet goes into the <head>:
<script src="https://chat.example/widget.js" async></script>
A week later, the show pages’ INP at the 75th percentile has gone from 130 ms to 290 ms. In most of the slow lines, script names widget.js. FCP and LCP didn’t change.
On the phone profile, a trace of the load shows one Evaluate script task of 340 ms for widget.js. It starts at about 1.9 s, 0.6 s after the first paint, with hundreds of Compile code events inside it. Coverage shows 81% of widget.js unused after the load. Leo says few buyers ever open the chat.
Why did INP get worse while FCP and LCP did not, and what would you change?
Hint 1
async changes when the download blocks the page. Does it change when the script runs?
Hint 2
Which part of a tap’s INP grows when a task is already running as the finger lands (Module 5)? And how many buyers need the chat at the moment the page loads?
Answer
async lets the page paint without waiting for widget.js, so FCP and LCP stay the same. But its run is one 340 ms main-thread task that starts when the file arrives, 0.6 s after the Buy button appears. A buyer who taps then waits for the task to end: a long input delay, in the field as in Figure 8’s async row.
The unused 81% belongs to the provider, so TinyTickets can’t remove it. But it can decide when the script loads. Few buyers open the chat, so a facade fits: a plain chat button that looks like the widget’s and loads widget.js on the first tap.
The cost is that tap: the buyer waits for the download and the 340 ms setup, so the button should show that the chat is loading. If the provider must show unread messages before a tap, load the script after load instead, as Fix 2 does.
Review questions
analytics.jsis 267 KB and arrives as 66 KB. Which size decides the work of parsing and compiling it, and which parts of that work run on the main thread?- After Fix 5, the first tap on Find the best 2 seats had a shorter INP, yet the buyer waited longer for the seats. Why, and what did TinyTickets add to remove most of the wait?
- Coverage showed 73% of the seat map’s lodash file and 66.5% of
payment.jsunused. What does “unused” mean there, and why can TinyTickets act on the first number but not on the second? import { chunk, minBy, range }added 71 KB fromlodashand about 17.6 KB fromlodash-es. Why the difference, and why wasn’t it 3 KB?- After Fix 3, which files get
max-age=31536000, immutable, which keepno-cache, and why doesseats.htmlname the shared chunk in amodulepreloadlink?
Answers
- The uncompressed 267 KB. With streaming compilation, the first parse and compile of the top-level code run on a background thread while the bytes arrive. The run of the top-level code, and the compile of each lazily parsed function on its first call, run on the main thread.
- The handler stops at
await import(), so the browser paints the next frame at once, and Event Timing ends there. The seats change one round trip later, when the chunk has arrived. TinyTickets loads the chunk in advance, withimport()once the page is idle afterload. - “Unused” means the code didn’t run while the panel recorded; it may still run later or elsewhere. Lodash is a file TinyTickets ships, so it can import less of it.
payment.jsis the provider’s code, served from its servers, so TinyTickets can only choose where and when it loads. lodashis a CommonJS package, so the bundler can’t tell which parts the three functions use and keeps all of it.lodash-esusesimportandexport, so tree shaking drops what nothing reaches.minByalone brings about 16 KB. Its second argument may be a property name or a pattern as well as a function, and the code for all three comes with it.- The hashed files in
/assets/and the pictures get a year; the HTML keepsno-cacheand anETag, because it names the current hashes. The browser learns of a module’s imports only after the module arrives, so without the link the chunk would start one round trip later.
Lab: weigh the scripts, then move and shrink them
Time: about 15 minutes. You need the lab app from Module 6 with the changes from “Reproduce Tuesday’s release in the lab”, Chrome and Node.js. The finished code is in the course repository, folder module-07/.
- Run
node third-party/make-fakes.js, thennode server.js. Openhttp://localhost:8080/show.htmlin Chrome, open DevTools, and set the phone profile: 412 × 823 with touch, CPU “6x slowdown”, Network “Slow 4G”, Disable cache checked. - Record a load in the Performance panel. Find the two Evaluate script tasks, then check Dim 3rd parties. Click the Compile script event above one of them, and read its Streamed line. Predict before you look: how many Compile code events sit inside the
analytics.jstask? - Block
analytics.jsfrom the Network panel’s context menu, and record a reload. Write down FCP from the recording. Unblock it, blockpayment.js, and reload again. - Open
seats.html, open the Coverage panel with Per block, and reload. Write down the unused share oflodash.min.js. Tap Find the best 2 seats and read it again. - Apply Fixes 1 and 2. Record the show page again. When does the analytics task run now?
- Apply Fix 3 and run
npm run build. Find lodash’s share of the seat map’s file in the printed tree. Then apply Fix 4 and predict the new size before you build. - Apply Fix 5, open the Network panel, and tap Find the best 2 seats twice. Which tap requests a file, and how long until the seats change?
Results from one run
These come from headless Chrome 157 on a 2019 laptop (Intel Core i7-9750H), through the DevTools Protocol, not the DevTools UI. Dim 3rd parties and the Coverage panel’s own view weren’t checked. Your numbers will differ.
- Step 2: the
analytics.jstask had 500 Compile code events, one per function its setup calls; its Compile script event was streamed. - Step 3: with
analytics.jsblocked, FCP was 1,304–1,336 ms; withpayment.jsblocked, 1,992–2,004 ms. - Step 4:
lodash.min.jswas 73.3% unused after the load and 71.9% after one tap. - Step 5: FCP 1,296–1,308 ms; the analytics task ran at about 2.9 s, a second after
load. - Step 6: lodash was 97.1% of a 73.2kb file; with
lodash-es, the file was 19.2kb. - Step 7: the first tap requested the chunk, and the seats changed 701–712 ms after it; the second tap requested nothing, and the seats changed after 78–84 ms.
Stretch: add //# allFunctionsCalledOnLoad as the first line of a copy of analytics.js, reload, and open its Compile script event. What changes in the details, and what happens to the Compile code events in the task?
What to look for
In two recorded runs through the protocol, the analytics.js task had no Compile code events, against 500 before: V8 compiled every function on the background thread. The background parse grew from about 14 ms to 20–23 ms, because it now compiles all 1,600 functions. The task itself took 312–368 ms, against 317–332 ms without the hint, so the saving of at most 54 ms didn’t show in two runs. DevTools’ source prints Compiling all functions eagerly in the details of such an event; these runs didn’t check the panel.
Cheat sheet
Heavy JavaScript and third parties
1. A script costs download, parse, compile and run; the main thread runs it
2. Streaming compiles top-level code off the main thread; lazy ones run on it
3. async moves the download, not the run, which is one task on arrival
4. Weigh a third party by blocking it; grouped by party in the Summary
5. Load each third party only on pages that need it, then after load
6. Coverage: unused means "didn't run while the panel recorded"
7. Bundle, read the tree, prefer ES-module packages so tree shaking works
8. import() moves code to first use, and adds a round trip there
9. Hashed names + immutable for files; no-cache for the HTML
Figure 12 is the whole module in one picture: whose code it is decides what you can change.
[script] [what you can change] [fix]
third party, blocks ---> when it loads ---> after load, when idle;
first paint not in a prerender
third party, long ---> where it loads ---> only on the page that
task after paint needs it; a facade
your code, bytes ---> what you ship ---> bundle, tree shaking,
that never run import() for rare code
your code, runs at ---> what it does ---> do less: one pass, not
load, every byte two
any file, second ---> its name and cache ---> hashed names, a year
visit of cache
Figure 12: you can’t shorten a third party’s task, only move it; your own code you can cut.
Next, in Module 8, buyers keep the waiting page open for 30 minutes before a 10:00 sale, and some phones slow down or reload the tab.
Sources
- What V8 does with a script: the cost of JavaScript in 2019, blazingly fast parsing: lazy parsing, explicit compile hints, code caching for JavaScript developers, Sparkplug, Maglev.
- Script loading: MDN,
<script>, HTML Standard, scripting, MDN,requestIdleCallback(), MDN,document.prerendering. - Third parties: third-party JavaScript, efficiently load third-party JavaScript, identify slow third-party JavaScript, third parties insight, lazy load third-party resources with facades, Partytown trade-offs, Third Party Web.
- DevTools: Coverage, Request conditions, Performance panel reference, JavaScript code coverage in V8.
- Bundling: esbuild API, webpack, tree shaking, code splitting on web.dev, MDN,
import(), MDN,modulepreload, web.dev,modulepreload, HTTP cache. - For going deeper: the preparser post, on why a function is parsed at most twice.
TimelineUIUtils.tsin DevTools’ source, on what a compile event’s details can say. The third-party-web repository, whose entity list decides what DevTools calls a third party.