From 8af9ef1c1e6ecdfb3bea6be8ccdc651c265da083 Mon Sep 17 00:00:00 2001 From: Randy Date: Thu, 8 Oct 2026 17:11:13 +0800 Subject: [PATCH] docs(skill): observers-first guidance for userscript reactivity The userscript reactivity section only said to prefer a MutationObserver over polling "to wait for an element". It was silent on the geometry/animation-tracking case, which is exactly where a self-scheduling requestAnimationFrame loop creeps in and burns a core on an idle page (a shipped bilibili card-blocker did this). Expand it into "Reacting to change: observers first": a signal -> observer table (MutationObserver, ResizeObserver, IntersectionObserver, PerformanceObserver, ReportingObserver, plus the event-based matchMedia/visualViewport/navigation equivalents), the fallback ladder (observer -> discrete event -> one-shot setTimeout -> bounded rAF), the anti-patterns, and the cases that have no observer at all. Point --print-skill's Userscripts section at the new section. Co-Authored-By: Claude --- skill/userscripts.md | 90 ++++++++++++++++++++++++++++-- src/browserwright/skill_runtime.md | 8 ++- 2 files changed, 90 insertions(+), 8 deletions(-) diff --git a/skill/userscripts.md b/skill/userscripts.md index 3143187..d70a72f 100644 --- a/skill/userscripts.md +++ b/skill/userscripts.md @@ -42,11 +42,88 @@ Supported v1 metadata directives: - No automatic watch mode; push explicitly after each edit. - The popup shows matching scripts for the current site with per-script toggles and a master switch. -## Reacting to dynamic pages - -Most target sites render after load, swap content in place, or route without a full page load (SPAs), so the element a script wants often is not there at `document-idle`. Prefer a `MutationObserver` over polling (`setInterval`, `setTimeout` retry loops) to wait for it: the observer fires exactly when the DOM changes, costs nothing while the page is idle, and keeps working across SPA navigations, whereas polling burns CPU on every tick and still fires late. - -A reusable helper — call `cb` once for every element matching `selector`, now and whenever one appears later: +## Reacting to change: observers first + +Most target sites render after load, swap content in place, or route without a full page load (SPAs), so the element a script wants often is not there at `document-idle`. + +The rule for all of it: + +> **Reach for an observer first. If no observer can express the signal, use the event +> that already fires on the change. Only when neither exists fall back to a timer — +> a one-shot `setTimeout`, or a bounded `requestAnimationFrame` — and never to a +> polling loop.** + +An observer is scheduled by the browser, fires exactly when the change happens, +and costs nothing while the page is idle. Polling (`setInterval`, or a +`setTimeout` retry loop re-querying the DOM) burns CPU on every tick, fires +late, and keeps firing after the page has settled. A page can also change before +`document-idle`; if you need to catch that, inject with `@run-at document-start`. + +### Pick the observer by the signal, not by habit + +| You want to react to… | Use | Notes | +| --- | --- | --- | +| nodes added / removed / replaced | `MutationObserver({childList:true, subtree:true})` | observe the narrowest stable container, not `document` | +| an attribute, `class`, or text change | `MutationObserver({attributes:true})` / `{characterData:true}` | add `attributeFilter:[…]` to cut noise; `attributeOldValue`/`characterDataOldValue` to read the previous value | +| an element's box size changed | `ResizeObserver` | the tool for "a native control animates its own width", lazy images settling, layout reflow | +| is it on screen / near the viewport | `IntersectionObserver` | `rootMargin` to prefetch, `threshold` for partial visibility; `scrollMargin` for scroll containers | +| …and it must not be occluded | `IntersectionObserver({trackVisibility:true})` | Chrome-only; read `entry.isVisible` | +| a page-load / resource / layout-shift / long-task signal | `PerformanceObserver({type, buffered:true})` | `PerformanceObserver.supportedEntryTypes` lists what this browser supports | +| a browser deprecation, intervention, or CSP violation | `ReportingObserver({types:[…], buffered:true})` | explains otherwise-mysterious breakage | +| viewport, dark mode, reduced motion | `matchMedia(q).addEventListener("change", …)` | an event, not an `*Observer` interface, but the same job | +| SPA route change | the `navigation` `navigate` event; else `popstate`/`hashchange` + a `MutationObserver` on the app root | | +| mobile keyboard / visual viewport | `visualViewport` `resize`/`scroll` | | +| tab hidden/shown, page frozen/restored | `visibilitychange`, `pageshow`/`pagehide`, `freeze`/`resume` | | +| a CSS transition or animation finished | `transitionend` / `animationend`, or `el.getAnimations()` + `Animation.finished` | no observer needed — the event is the signal | +| fonts finished loading | `document.fonts.ready` / `"loadingdone"` | | + +Browser support (MDN): `MutationObserver`, `ResizeObserver`, `IntersectionObserver`, +`PerformanceObserver`, `ReportingObserver`, and `matchMedia` change events are all +Baseline / widely available in the Chrome that the extension backend runs. +Experimental or Chrome-only — **check support before relying on it**: +`IntersectionObserver.trackVisibility` and `.delay`, `ResizeObserver` +`box:"device-pixel-content-box"`, `PressureObserver` (compute pressure, Chrome +desktop only), and `FileSystemObserver` (non-standard, origin trial). There is +**no `StyleObserver`**, and no observer at all for canvas pixels, network +response bodies, or another world's JS variables — see below. + +### The fallback ladder (only when no observer fits) + +1. **A discrete DOM/CSS event** — still event-driven and free while idle: + `transitionend`, `visibilitychange`, a `matchMedia` change, SPA nav events, + `focus`/`blur`, `input`. Prefer it over an observer when the change already + emits an event. +2. **One-shot `setTimeout`** — to wait a known settle window (let the page paint + after a navigation), or to *debounce* an observer burst into a single pass + (`setTimeout(fn, 0..250)` behind a queued flag). One shot, not a loop. +3. **`requestAnimationFrame`** — only to sample per-frame geometry that no + observer covers: an element moved by a CSS `transform`, a scroll-driven + position, an overlay that must track a moving box. It **must be started by a + real event and be bounded** — cap the self-scheduled frames, or stop when the + geometry stops changing. An unbounded + `function loop(){ …; requestAnimationFrame(loop) }` runs at ~60fps forever with + the mouse parked; that is the classic "the userscript is eating a core" bug + (a shipped bilibili card-blocker did exactly this). + +Never `setInterval` for DOM state. Never a `setTimeout` retry loop that polls +`querySelector` every N ms. + +### No observer exists for these + +- **A JS variable in the page's world changed.** You cannot observe it from the + isolated `USER_SCRIPT` world; read it on demand, or move to `@inject-into page` + and wrap the setter / install a `Proxy`. +- **Computed style changed without a box change.** No `StyleObserver`; use the + `transition*`/`animation*` events, or observe the element that does resize. +- **Network responses / `fetch` bodies.** Not an observer; hook `fetch`/`XHR` + from `@inject-into page`, or watch `PerformanceObserver` `resource` entries for + timing only (no body). +- **Canvas / WebGL pixels.** No observer; hook the draw calls in the page world. +- **User input.** Plain DOM events, not observers. + +### A MutationObserver helper + +Call `cb` once for every element matching `selector`, now and whenever one appears later — the "wait for the element the SPA hasn't rendered yet" case: ```javascript function onElement(selector, cb, root = document) { @@ -66,9 +143,10 @@ function onElement(selector, cb, root = document) { onElement("article.post", (post) => post.classList.add("us-highlight")); ``` -- Observe the narrowest stable container you can (a feed list, not `document`) — every mutation under it re-runs the callback. +- Observe the narrowest stable container you can (a feed list, not `document`) — every mutation under it re-runs the callback. A `subtree:true` observer on `documentElement` that re-queries the whole document on every record is a CPU sink on a busy page; debounce the burst into one pass. - Mark handled elements (`dataset`) so repeated callbacks never double-apply a change. - `disconnect()` when the job is one-shot (waiting for a single element); keep the observer when content keeps arriving (feeds, infinite scroll, SPA route changes). +- Keep a `ResizeObserver`/`IntersectionObserver` reference if you observe and later need to `unobserve` — and never resize an element inside its own `ResizeObserver` callback without an `expected size` guard (it logs `ResizeObserver loop completed with undelivered notifications`). ## Golden workflow diff --git a/src/browserwright/skill_runtime.md b/src/browserwright/skill_runtime.md index 4a8ac73..883e02e 100644 --- a/src/browserwright/skill_runtime.md +++ b/src/browserwright/skill_runtime.md @@ -533,8 +533,12 @@ browserwright userscript remove ``` Before writing one, read `userscripts.md` in this skill directory — in -particular "Reacting to dynamic pages": prefer a `MutationObserver` over -polling for elements. +particular "Reacting to change: observers first". Prefer an observer +(`MutationObserver`, `ResizeObserver`, `IntersectionObserver`, +`PerformanceObserver`, `ReportingObserver`) over polling; when none fits, use the +event that fires on the change, and only then a one-shot `setTimeout` or a +**bounded** `requestAnimationFrame` — never `setInterval` or an unbounded rAF +loop. ## Reporting browserwright bugs