Skip to content

Commit f270347

Browse files
authored
perf(site): cut forced style recalcs on load (#62421)
1 parent 2013807 commit f270347

9 files changed

Lines changed: 175 additions & 8 deletions

File tree

‎bun.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎services/site/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"@babel/core": "7.29.7",
4747
"@cloudflare/build-output-utils": "0.8.5",
4848
"@cloudflare/config": "0.23.0",
49+
"@hona/strobe": "catalog:",
4950
"@mdx-js/mdx": "3.1.1",
5051
"@types/babel__core": "7.20.5",
5152
"@types/bun": "catalog:",

‎services/site/perf/.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
github-snapshot.json

‎services/site/perf/serve.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Serves the production build that script/build.ts wrote (.cloudflare/output) in workerd through
2+
// Miniflare, the runtime check-worker-start.ts uses, for strobe benches (strobe.json `serve`). Every
3+
// outbound fetch gets a 503, as in check-worker-start.ts, so both sides of a bench render the
4+
// build-time GitHub snapshot and no live data.
5+
//
6+
// bun perf/serve.ts --port 4300
7+
import path from "node:path"
8+
import { parseArgs } from "node:util"
9+
import { readBuildOutput } from "@cloudflare/build-output-utils"
10+
import { Miniflare, Response } from "miniflare"
11+
12+
const args = parseArgs({ options: { port: { type: "string", default: "4300" } } })
13+
const root = path.resolve(import.meta.dir, "..")
14+
const worker = (await readBuildOutput(root)).workers.default
15+
const config = worker.config
16+
if (!worker.bundleDir || !config.manifest) throw new Error("perf/serve: the Build Output has no Worker bundle")
17+
const bundle = worker.bundleDir
18+
const modules = Object.fromEntries(
19+
await Promise.all(
20+
Object.entries(config.manifest.modules).map(async ([name, module]) => {
21+
const file = Bun.file(path.join(bundle, name))
22+
const contents = module.type === "esm" || module.type === "cjs" ? await file.text() : await file.bytes()
23+
return [name, { type: module.type, contents }] as const
24+
}),
25+
),
26+
)
27+
const env = Object.fromEntries(
28+
Object.entries(config.env ?? {}).map(([name, binding]) => {
29+
if (binding.type === "text") return [name, { type: "text" as const, value: binding.value }]
30+
if (binding.type === "assets") return [name, { type: "assets" as const }]
31+
throw new Error(`perf/serve: the ${binding.type} binding ${name} is not emulated`)
32+
}),
33+
)
34+
35+
const miniflare = new Miniflare({
36+
cf: false,
37+
host: "127.0.0.1",
38+
port: Number(args.values.port),
39+
workers: [
40+
{
41+
config: {
42+
name: config.name,
43+
compatibilityDate: config.compatibilityDate,
44+
compatibilityFlags: config.compatibilityFlags,
45+
triggers: [{ type: "fetch", pattern: "*/*" }],
46+
env,
47+
manifest: { mainModule: config.manifest.mainModule, modules },
48+
...(worker.assetsDir ? { assets: { ...config.assets, directory: worker.assetsDir } } : {}),
49+
},
50+
dev: {
51+
outboundService: { type: "fetcher", handler: () => new Response("offline", { status: 503 }) },
52+
},
53+
},
54+
],
55+
})
56+
console.log(`perf/serve: ${config.name} at ${await miniflare.ready}`)
57+
for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, () => void miniflare.dispose().finally(() => process.exit(0)))

‎services/site/perf/site.bench.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// Main-thread work on the site's pages and interactions, for strobe (https://github.com/Hona/strobe).
2+
// Each variant is the production build (script/build.ts) served in workerd by perf/serve.ts.
3+
//
4+
// strobe bench services/site/perf/site.bench.ts --base origin/dev --head . --headless
5+
//
6+
// Loads are returning visits: each run navigates from about:blank with the HTTP cache warm, so they
7+
// measure parsing, running and hydrating the page's code, not the network. Interactions start from a
8+
// fresh load of the home page, so each run is the first ⌘K, hover or click after a load.
9+
import { bench, url, web, type Context, type RunCase } from "@hona/strobe"
10+
11+
const desktop = { width: 1440, height: 900 }
12+
const phone = { width: 390, height: 844 }
13+
const card = '[data-component="products"][data-layout="carousel"] [data-component="product-card"] [data-slot="media"]'
14+
15+
// Absolute: page.goto resolves a relative path against about:blank after the reset.
16+
const load = (path: string): RunCase<unknown> => ({
17+
primary: "main.work",
18+
run: async (ctx) => {
19+
await ctx.page.goto(new URL(path, ctx.url).href)
20+
await ctx.page.idle()
21+
},
22+
reset: (ctx) => ctx.page.goto("about:blank"),
23+
})
24+
25+
const reload = async (ctx: Context<unknown>) => {
26+
await ctx.page.goto(new URL("/", ctx.url).href)
27+
await ctx.page.idle()
28+
}
29+
30+
export default bench({
31+
targets: {
32+
desktop: web({ url: "/", viewport: desktop }),
33+
phone: web({ url: "/", viewport: phone, scale: 3 }),
34+
// The live site, for reference only: `--target production --blocks 5 --head .` (nothing to build).
35+
production: url("https://opencode.ai/", { viewport: desktop }),
36+
},
37+
async setup({ page }) {
38+
await page.idle()
39+
},
40+
cases: {
41+
"load-home": load("/"),
42+
"load-product": { ...load("/product"), targets: ["desktop", "production"] },
43+
"load-desktop": { ...load("/desktop"), targets: ["desktop", "production"] },
44+
"load-docs": { ...load("/docs/"), targets: ["desktop", "production"] },
45+
"scroll-home": {
46+
primary: "main.work",
47+
targets: ["desktop", "production"],
48+
run: ({ page }) => page.scroll("main", { by: 12000, speed: 6000 }),
49+
reset: reload,
50+
},
51+
search: {
52+
primary: "main.work",
53+
targets: ["desktop", "production"],
54+
run: async ({ page }) => {
55+
await page.press("ControlOrMeta+k", { until: '[data-component="site-search"] [role="dialog"]' })
56+
await page.idle()
57+
},
58+
reset: reload,
59+
},
60+
"card-hover": {
61+
primary: "main.work",
62+
targets: ["desktop", "production"],
63+
run: async ({ page }) => {
64+
await page.hover(card)
65+
await page.idle()
66+
},
67+
reset: async (ctx) => {
68+
await ctx.page.move(1, 1)
69+
await reload(ctx)
70+
},
71+
},
72+
"card-open": {
73+
primary: "main.work",
74+
run: async ({ page }) => {
75+
await page.click(card, { until: '[data-component="product-hero"]' })
76+
await page.idle()
77+
},
78+
reset: reload,
79+
},
80+
},
81+
})

‎services/site/src/component/site/console-field.tsx‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { createEffect, onCleanup, onMount } from "solid-js"
1+
import { createEffect, on, onCleanup, onMount } from "solid-js"
22

33
// The Console landing backdrop (dev.opencode.ai/console, preset "vertical" with dots): 2px dots
44
// where columns cross rows. Gaps are 24px at the centre and tighten to 8px at the edges
@@ -38,11 +38,10 @@ export function ConsoleField(props: { dot?: number }) {
3838
element.style.setProperty("--console-dots", `url(${canvas.toDataURL()})`)
3939
element.dataset.ready = ""
4040
}
41-
// Redraw when the dot size changes (switching between Console options).
42-
createEffect(() => {
43-
dot()
44-
draw()
45-
})
41+
// Redraw when the dot size changes (switching between Console options). The first draw is the
42+
// resize observer's first callback, after layout and before the frame paints, so mounting neither
43+
// forces a layout nor draws and encodes the mask twice.
44+
createEffect(on(dot, draw, { defer: true }))
4645
const resize = new ResizeObserver(draw)
4746
resize.observe(element)
4847

‎services/site/src/component/site/site-banner.tsx‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,16 @@ export function SiteBanner() {
6868
setDismissed(localStorage.getItem(dismissKey) ?? undefined)
6969
const host = banner?.parentElement
7070
const link = banner?.querySelector("a")
71+
// Reads come before the write, and an unchanged value isn't written again: --banner-scroll sits on
72+
// the page's root, so each write restyles the whole page, and a read after it forced that at once.
73+
// Unset reads as 0px (site-banner.css's fallback), so a page loaded at the top writes nothing.
74+
let offset = "0px"
7175
const scroll = () => {
72-
host?.style.setProperty("--banner-scroll", `${Math.min(window.scrollY, 200)}px`)
73-
setOnTop(window.scrollY < (link?.offsetHeight ?? 0))
76+
const y = window.scrollY
77+
const top = y < (link?.offsetHeight ?? 0)
78+
const next = `${Math.min(y, 200)}px`
79+
if (next !== offset) host?.style.setProperty("--banner-scroll", (offset = next))
80+
setOnTop(top)
7481
}
7582
const paint = () => setBlue(link ? getComputedStyle(link).backgroundColor : undefined)
7683
// The blue changes with the theme (the host's data-theme, or the system's when it follows it)

‎services/site/strobe.json‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"$schema": "./node_modules/@hona/strobe/schema/strobe.v1.json",
3+
"build": {
4+
// A pinned GitHub snapshot (perf/github-snapshot.json, when present) and a token GitHub refuses
5+
// keep every build's star counts and release list the same, so base and head render one page.
6+
"command": "bun install --frozen-lockfile && (test ! -f perf/github-snapshot.json || cp perf/github-snapshot.json src/lib/github-snapshot.json) && bun script/build.ts --mode production",
7+
"cwd": "services/site",
8+
"output": "services/site/.cloudflare/output",
9+
"env": { "GITHUB_TOKEN": "strobe-pinned-snapshot" },
10+
},
11+
"serve": {
12+
"command": "bun perf/serve.ts --port {port}",
13+
"cwd": "services/site",
14+
"ready": "http://127.0.0.1:{port}/",
15+
},
16+
"harness": ["services/site/perf", "services/site/vite.config.ts"],
17+
}

‎services/site/vite.config.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,9 @@ export default defineConfig({
181181
// Oxc, Vite 8's own minifier. "esbuild" here left the bundles unminified: Vite only adds its
182182
// esbuild minifier when the top-level build.minify asks for it, and that stays off for the Worker.
183183
minify: "oxc",
184+
// strobe builds with STROBE_SOURCEMAP=hidden: maps beside the scripts without a
185+
// sourceMappingURL comment, so the scripts stay byte for byte and profiles name source lines.
186+
sourcemap: process.env.STROBE_SOURCEMAP === "hidden" ? "hidden" : undefined,
184187
},
185188
},
186189
},

0 commit comments

Comments
 (0)