From d8aa79127a555932fb6d8fbd7bc31bb58d199654 Mon Sep 17 00:00:00 2001 From: Stephanie Hobson Date: Wed, 18 Nov 2026 15:29:50 -0700 Subject: [PATCH 01/12] Add ExecPlan for first-load performance (#516) --- .../2026-11-18-first-load-performance.md | 452 ++++++++++++++++++ 1 file changed, 452 insertions(+) create mode 100644 docs/execplans/2026-11-18-first-load-performance.md diff --git a/docs/execplans/2026-11-18-first-load-performance.md b/docs/execplans/2026-11-18-first-load-performance.md new file mode 100644 index 00000000..2906923b --- /dev/null +++ b/docs/execplans/2026-11-18-first-load-performance.md @@ -0,0 +1,452 @@ +# Make the first visit to a page paint and fill in sooner + +This ExecPlan is a living document. The sections `Progress`, `Surprises & Discoveries`, +`Decision Log`, and `Outcomes & Retrospective` must be kept up to date as work proceeds. It is +maintained in accordance with `.claude/skills/execplans/references/PLANS.md`, including its +"Ensemble addendum", which overrides the upstream text where the two disagree. + +## Purpose / Big Picture + +A first-time visitor to sees a blank white page +until about 200 KB of JavaScript has downloaded and run. Then they see a spinner while the page +fetches more code. Only after that does it start asking for the dashboard's data. On a slow phone +connection each of those steps is a visible wait, and they happen one after another. This is issue +#516 (), a list of routes to explore for faster +first loads. + +After this work, the site header and navigation appear as soon as the stylesheet arrives, before any +JavaScript runs. The code for every page downloads alongside the main script instead of after it. +A dashboard's data request starts as soon as the main script runs, not after the dashboard's own +code has arrived. The fonts are requested with the HTML, not after the stylesheet has been parsed. +Each change is kept only if a before-and-after measurement shows it helps. + +To see it working, build and serve the production bundle, open + in Chrome with DevTools' network throttling set to +"Slow 4G" and the cache disabled, and reload. The header shows up while the scripts are still +downloading. In the Network panel, the request for `user-activity/index.json` starts while the +`DashboardContainer-*.js` chunk is still downloading, not after it finishes. + +Scope is "measure, then quick wins". These are out of scope and will be listed as follow-ups in +`Outcomes & Retrospective`: + +- Prerendering pages at build time and switching React to hydrate them. +- Changing the CDN's cache headers. +- Asking the transposer to inline metric data into the dashboard file. +- A performance budget in CI. +- Replacing the dashboard-level spinner with a skeleton of the dashboard. + +## Progress + +- [x] (2026-11-18) Drafted the plan on branch `516--first-load-performance`, cut from + `468--fresh-paint` (PR #512). +- [ ] Milestone 1: baseline measurement and bundle composition. +- [ ] Milestone 2: start the dashboard data request at startup. +- [ ] Milestone 3: preload hints in the built `index.html`. +- [ ] Milestone 4: static page shell in `index.html`. +- [ ] Milestone 5: fixes the measurements still call for (font fallback metrics, analytics timing, + early metric requests), each only if justified. +- [ ] Milestone 6: final measurement, clean-up, full test run, retrospective. + +## Surprises & Discoveries + +None yet. + +## Decision Log + +- Decision: stack this branch on `468--fresh-paint` (PR #512) rather than on `main`. + Rationale: #512 replaces the Fira Sans webfonts (WOFF, TTF and SVG, no `font-display`) with + Mozilla Headline and Mozilla Text WOFF2 files that already use `font-display: swap`. Tuning the + Fira faces would be thrown away when #512 merges. Every font measurement here is of the fonts that + will ship. Rebase onto `main` once #512 merges, and onto `468--fresh-paint` whenever it changes + before then. + Date/Author: 2026-11-18, Stephanie Hobson. +- Decision: limit the scope to measuring and the low-risk changes. Prerendering, CDN headers, + transposer changes and a CI budget become follow-ups. + Rationale: each of the excluded items either needs another team (CDN, transposer) or changes how + the app boots (hydration). They deserve their own plans once this one has shown where the time + actually goes. + Date/Author: 2026-11-18, Stephanie Hobson. +- Decision: the measurement script is throwaway. It isn't committed, and it's deleted in + Milestone 6. Behaviour that can regress gets a committed Playwright spec or Vitest test instead. + Rationale: timing numbers from a shared CI runner are too noisy to gate merges on. A spec that + checks *order* (this request started before that one finished) or *presence* (these tags are in + the HTML) is deterministic. `docs/execplans/2026-10-28-hardware-resize-performance.md` worked the + same way. + Date/Author: 2026-11-18, Stephanie Hobson. + +## Outcomes & Retrospective + +Not started. + +## Context and Orientation + +The site is a client-rendered React 18 single-page app built with Vite. "Client-rendered" means the +HTML the server sends, `index.html` at the repository root, holds an empty `
` and a +script tag. Everything visible is drawn by JavaScript after it downloads and runs. `src/index.jsx` is +the entry point. It calls React's `createRoot(...).render(...)`, and React replaces whatever is +inside `#root` when it first renders. The site has no data of its own. Every number comes from JSON +files under `https://data.firefox.com/datasets/`, written weekly by a separate project, the +transposer. + +Issue #516 asks for an investigation of render-blocking requests, network request chains, font +loading, layout shifts, page skeletons and rehydration. It points out that the app has no server +rendering, so there is no rehydration today. It also suggests measuring a baseline before changing +anything. + +These are the pieces of the repository this plan touches, and the terms it uses for them: + +- **Route chunks and `lazyLoad`.** `src/components/views/Main.jsx` declares the routes (`/`, + `/contact`, `/dashboard/`, and a catch-all Not Found). It wraps each page component in + `lazyLoad(() => import(...))` from `src/lib/lazyLoad.jsx`. Each `import()` becomes a separate + JavaScript file, a *chunk*, in the build, such as `build/assets/DashboardContainer-.js`. + `lazyLoad` calls the import **as soon as its module is evaluated**, not when the page is first + shown. `src/components/views/MetricOverview.jsx` does the same for `ChartContainer`, + `DataTableContainer` and `CustomizableDateContainer`. So every chunk is downloaded on every page, + but none of them starts until the main script `index-.js` has finished downloading and + started running. `src/lib/LazyBoundary.jsx` shows a spinner while a chunk is still loading. +- **The data layer, `withFetch` and `fetchCache`.** `src/lib/withFetch.jsx` wraps a container + component and fetches the URL its function returns. `src/components/containers/DashboardContainer.jsx` + fetches `${props.source}/index.json`, where `source` comes from the dashboard's entry in + `src/config.json`. The function `cachedFetch(url)` in `withFetch.jsx`, not exported today, stores + each request in the `Map` exported by `src/lib/fetchCache.js`. A later request for the same URL + joins the one in flight or reuses its result, until the page reloads. So a request started early + by other code is picked up by the container when it mounts, without a second network request. +- **The dashboard request chain.** On a first visit to a dashboard, the browser fetches in this + order, with each step waiting on the one before: + 1. the HTML; + 2. `index-*.js`; + 3. the `DashboardContainer-*.js` chunk (about 178 KB on the last local build); + 4. the dashboard's `index.json`; + 5. one `index.json` per metric. + + Step 4 depends on nothing in step 3 except the URL, and that URL can be worked out from + `src/config.json` and the page's path. +- **Data URLs are absolute.** The `source` values in `src/config.json` are full + `https://data.firefox.com/...` URLs. In production they are same-origin. Locally and on stage they + are cross-origin. `fetchJSON` in `withFetch.jsx` requests them with `mode: 'cors'` and + `credentials: 'same-origin'`. +- **Styles and fonts.** Styles are written in Stylus under `src/components/views/styl/` and compiled + to the gitignored `src/components/views/css/` by `npm run build:css`. `npm start` and + `npm run build` both do this for you. Views import the compiled CSS. On this branch, + `Application.styl` declares the `@font-face` rules for `Mozilla Headline VF` and `Mozilla Text VF` + (WOFF2, `font-display: swap`). The fallback stack in `includes/lib.styl` is system UI fonts. Vite + copies the font files into `build/assets/` with a content hash in the name. The browser only + discovers it needs them after downloading and parsing the CSS, and only for text that is actually + on screen. +- **Analytics.** `src/components/decorators/withTracker.jsx` calls `ReactGA.initialize` from + react-ga4 when the module is evaluated. That adds Google's gtag script to the page. The checked-in + `.env` holds a placeholder measurement ID. +- **Deploy.** `.github/workflows/deploy.yml` uploads `build/` to a Google Cloud Storage bucket + behind Google's CDN. It copies the same `build/index.html` to each route path, so anything added + to `index.html` applies to every page. `docs/architecture/deploy.md` records that the CDN rewrites + every `cache-control` header to `public,max-age=0`, so even content-hashed assets are revalidated + on each visit. That's a follow-up, not something this plan changes. +- **Web performance terms.** + - *FCP* (First Contentful Paint) is when the first text or image appears. + - *LCP* (Largest Contentful Paint) is when the largest one appears. + - *CLS* (Cumulative Layout Shift) is a score for how much visible content jumps after it has + appeared. 0 is perfect, and Google treats under 0.1 as good. The browser reports each shift as a + `layout-shift` performance entry, naming the elements that moved. + - A *preload* (``) tells the browser to fetch a file now because it will be + needed shortly. A *modulepreload* does the same for a JavaScript module, and also parses it. + - A *render-blocking* request is a stylesheet or synchronous script in the head. The browser won't + paint anything until it arrives. +- **Test helpers.** + - `tests/playwright/fixtureData.js` exports a Playwright `test` that answers `data.firefox.com` + requests from the recordings in `tests/playwright/fixtures/`, or passes them through to live + data in the `live-data` project. + - `holdRequests(page, matcher, handler)` in `tests/playwright/utils.js` pauses matching requests + until the function it returns is called. `tests/playwright/specs/fixtures/placeholders.spec.js` + shows it in use. + - `tests/playwright/specs/jsDisabled.spec.js` runs with JavaScript off and asserts that + `#application`, the root element `views/Application.jsx` renders, is absent. Any static markup + added to `index.html` must not use that id. + - Playwright runs against the Vite dev server (`npm start`, port 3000), not a production build. + Vitest only runs files matching `src/tests/jest/**/*.test.jsx`. + +## Plan of Work + +### Milestone 1: measure the baseline (prototyping) + +Nothing in the issue has been measured, so this milestone finds out where a first visit's time +actually goes, and decides which of the later milestones are worth doing. + +Write a throwaway Node script, `scripts/measureLoad.js`. Don't commit it. Start it with +`/* eslint-disable no-console */`, because `npm run lint` lints every file in the tree and the +project forbids `console`. It uses `@playwright/test`'s +`chromium` launcher. For each of `/` and `/dashboard/user-activity`, it opens a fresh browser +context (so the cache is cold) and uses a CDP session to: + +- emulate a slow mobile network: `Network.emulateNetworkConditions` with about 400 ms latency, + about 400 kbit/s down and 400 kbit/s up, which is DevTools' "Slow 4G"; +- slow the CPU fourfold with `Emulation.setCPUThrottlingRate`. + +Before the page's own scripts run, it installs `PerformanceObserver`s through `page.addInitScript` +for `paint`, `largest-contentful-paint` and `layout-shift` (with `buffered: true`). It keeps each +layout shift's value and the elements in its `sources`. It waits until the last metric chart is on +screen, or for 5 seconds of network quiet on `/`. It then prints: + +- FCP, LCP and total CLS; +- each layout shift with its sources; +- the waterfall: from `performance.getEntriesByType('resource')`, each request's name, `startTime`, + `responseEnd` and `transferSize`. + +Run each page five times and report medians. + +Run it against a production build served locally: `npm run build`, then `npx vite preview --port +4173`, which serves `build/` with deep links working. Data comes from live `data.firefox.com`. Run +it once more against itself. Production serves `main` rather than this +branch, but that run records what only the real server can show: the response's +`content-encoding`, the HTTP protocol, and whether the gtag script loads and when. Also run +`npm run size` and note what the largest modules in the main bundle are. + +Write the results into `Surprises & Discoveries` as a short table, and the per-step waterfall for +the dashboard. Then, in the `Decision Log`, state which of Milestones 2–5 the numbers justify. Drop +a milestone if its step isn't on the critical path. For example, if the dashboard chunk always +arrives before the data request would have finished anyway, Milestone 2 buys nothing. + +Acceptance: the table exists, with medians for both pages, and each later milestone is either +confirmed or dropped with a reason. This milestone changes no committed code, so no documentation +goes stale. + +### Milestone 2: start the dashboard data request at startup + +In `src/lib/withFetch.jsx`, export a named function `prefetchJSON(url)` that calls `cachedFetch(url)` +and returns nothing. It must swallow its own rejection with `.catch(() => {})` so that a failure +isn't an unhandled rejection. `cachedFetch` already forgets a failed request, so the container's own +request retries and reports the error as it does today. + +In `src/index.jsx`, before `createRoot(...)`, find the dashboard whose route matches +`window.location.pathname`. Use `matchPath` from `react-router` with the same +`/dashboard/${dashboard.key}` pattern `Main.jsx` uses, over `dashboards` from `src/config.json`. If +one matches, call `prefetchJSON(dashboardIndexUrl(dashboard.source))`. The URL must be built exactly +as `DashboardContainer.jsx` builds it, or the cache won't match. So add `dashboardIndexUrl(source)` to +`src/lib/utils.js` and use it in both places. It can't be exported from `DashboardContainer.jsx` +itself: importing that module from the entry would pull the dashboard chunk into the main bundle. + +Add `tests/playwright/specs/fixtures/early-data.spec.js`. It holds the dashboard chunk with +`holdRequests(page, url => url.pathname.includes('DashboardContainer'))`. That matches +`/src/components/containers/DashboardContainer.jsx` on the dev server and the hashed chunk in a +build. It then visits `/dashboard/user-activity` and waits for a request whose path ends with +`user-activity/index.json`, using `page.waitForRequest`, while the chunk is still held. Then it +releases the chunk and checks that the dashboard renders its title. Revert the `index.jsx` change +and confirm the spec fails (the request never comes while the chunk is held), then restore it. + +Add a Vitest case to the existing `src/tests/jest/withFetch.test.jsx`. It +stubs `window.fetch`, calls `prefetchJSON(url)`, awaits the response, then renders a component +wrapped by `withFetch` for the same URL. The component must render fulfilled on its first render, +and `fetch` must have been called once. + +Docs: the data-layer paragraph in `AGENTS.md` and the matching text in +`docs/architecture/frontend.md` say `withFetch` is used in exactly three files. Add that +`src/index.jsx` starts the current dashboard's request through `prefetchJSON`. Re-run the +measurement and record the dashboard's change in `Surprises & Discoveries`. + +Acceptance: `npm run test:jest` and `npm run test:playwright:recorded` pass, including the new spec, +and the spec fails with the change reverted. In the measurement, the dashboard `index.json` request +starts before the `DashboardContainer` chunk's `responseEnd`. + +### Milestone 3: preload hints in the built `index.html` + +Because `lazyLoad` starts every chunk anyway, telling the browser about them in the HTML costs no +extra bytes. It only moves their start from "after `index.js` runs" to "while the HTML is parsed". +The same goes for the fonts, which today wait for the CSS. + +Create `scripts/indexHtmlPlugin.mjs`, exporting a default function that returns a Vite plugin. Add +it to `plugins` in `vite.config.mjs`. The plugin has a `transformIndexHtml` hook with +`order: 'post'`. When the hook's context has a `bundle`, which happens only in `vite build`, it +returns tags to inject into the head: + +- `` for every JavaScript chunk in the bundle except + the entry chunk. Vite already preloads the entry and its static imports. +- `` for every CSS asset except the entry's stylesheet, + which is already a ``. +- `` for the assets whose + original names are `MozillaText-Variable.woff2` and `MozillaHeadline-Variable.woff2`. These are + the upright faces almost every page uses. The italic files are left to load on demand. + `crossorigin` is required on font preloads even for same-origin files, or the browser fetches the + font twice. + +Put the tag building in a separately exported pure function, `preloadTags(bundle)`. It takes Rollup's +bundle object (`{ fileName: { type: 'chunk' | 'asset', isEntry, fileName, names, ... } }`) and returns +Vite's `HtmlTagDescriptor` array. Test it from `src/tests/jest/indexHtmlPlugin.test.jsx` by +importing `../../../scripts/indexHtmlPlugin.mjs` and passing a hand-built bundle. Assert that the +entry chunk is skipped, that each other chunk gets a modulepreload, and that exactly the two +upright fonts get a font preload with `crossorigin`. + +`eslint.config.js` gives Node and browser globals only to `.js` and `.jsx` files. A `.mjs` file +gets the shared rules but no globals, which is fine as long as the plugin uses only imports. If it +needs a Node global such as `process`, import it from `node:process` rather than widening the lint +config. Run `npm run build` and `grep -E 'modulepreload|as="font"' build/index.html`, and +confirm the hashed names match files in `build/assets/`. Re-measure. + +Docs: `AGENTS.md`'s description of `vite.config.mjs` and `index.html`, and the deploy comment about +`index.html` being copied per route, stay accurate. Add one line to `AGENTS.md`'s project-structure +notes saying that `scripts/indexHtmlPlugin.mjs` injects preload hints at build time. + +Acceptance: the Vitest file passes. The built `index.html` contains the tags. In the measurement the +chunks' `startTime` falls before `index.js`'s `responseEnd`, and the fonts start before the CSS +finishes. + +### Milestone 4: static page shell in `index.html` + +Give the browser something real to paint before any JavaScript runs: the site header and navigation, +which are the same on every page. + +Extend `scripts/indexHtmlPlugin.mjs`. In both dev and build, `transformIndexHtml` replaces +`
` with a `#root` that already holds the shell, generated from +`src/config.json`. The shell is the same markup `src/components/views/Header.jsx` renders: a +`
` with an `h1` link to `/` and a `nav#main-navigation` list linking to each +`/dashboard/` with its `menuTitle`, then `/contact`. After the header comes an empty +`
`. Give `.page-shell` a `min-height` in `Application.styl` equal to +the height `main` has while the route spinner shows, so the footer doesn't jump when the app takes +over. The header's styles come from `Header.styl`. Check whether that CSS lands in the entry +stylesheet, which is render-blocking and in the head. If it doesn't, the shell paints unstyled, and +the fix is to import `Header.css` from `Application.jsx` so it does. Record which it was. + +React replaces the shell on its first render, with the same header in the same place, so nothing +should move. Don't use `id="application"`. + +Add `tests/playwright/specs/shell.spec.js` with: + +- **A drift guard.** It fetches the raw HTML with `request.get('/')`, extracts the `#main-header` + markup, loads `/`, and compares it with the rendered `#main-header`'s `outerHTML`. Normalise + whitespace before comparing. +- **A CLS check.** On `/dashboard/user-activity` it collects `layout-shift` entries through + `addInitScript`. It asserts that none of their sources lie inside `#main-header`. + +In `jsDisabled.spec.js`, add a test that the nav links are visible with JavaScript off and point to +`/dashboard/user-activity`, `/dashboard/usage-behavior`, `/dashboard/hardware` and `/contact`. + +Docs: `AGENTS.md` and `docs/architecture/frontend.md` both say `index.html` holds only the +`og:image`, `og:title` and `