From 6210f284d276a2bf97d8d3a038a1647d89cf6d62 Mon Sep 17 00:00:00 2001 From: saberzero1 Date: Mon, 9 Nov 2026 19:40:17 +0100 Subject: [PATCH] feat: prefetching (configuration.prefetch: viewport by default, hover, off), with and without SPA routing --- .changeset/prefetch.md | 11 + docs/configuration.md | 1 + docs/features/SPA Routing.md | 2 + docs/features/prefetching.md | 32 +++ globals.d.ts | 19 ++ quartz.config.default.yaml | 1 + quartz/cfg.ts | 6 + quartz/components/scripts/popover.inline.ts | 16 +- quartz/components/scripts/prefetch.inline.ts | 265 ++++++++++++++++++ quartz/components/scripts/spa.inline.ts | 45 +-- quartz/components/scripts/util.ts | 6 +- quartz/plugins/emitters/componentResources.ts | 14 + quartz/plugins/quartz-plugins.schema.json | 6 + 13 files changed, 399 insertions(+), 25 deletions(-) create mode 100644 .changeset/prefetch.md create mode 100644 docs/features/prefetching.md create mode 100644 quartz/components/scripts/prefetch.inline.ts diff --git a/.changeset/prefetch.md b/.changeset/prefetch.md new file mode 100644 index 000000000..647f5b2ea --- /dev/null +++ b/.changeset/prefetch.md @@ -0,0 +1,11 @@ +--- +"@jackyzha0/quartz": minor +--- + +Prefetching: Quartz fetches pages before their links are followed, so they open at once. New `configuration.prefetch`: + +- `viewport` (default): links on screen are fetched while the browser is idle, and links pointed at, focused or touched first. +- `hover`: only links pointed at, focused or touched. +- `"off"`. + +It works with and without SPA routing. With SPA routing, fetched pages are kept in memory (five minutes, at most 40) and used by both page navigation and popover previews, which no longer download a page the router fetches again. Without it, Quartz asks the browser to prefetch (Speculation Rules, or ``). Nothing is prefetched from links to other sites, files, or pages the site doesn't have, or with Data Saver on or a 2G connection (except links pointed at). Add `data-no-prefetch` to a link to exclude it. See https://quartz.jzhao.xyz/features/prefetching diff --git a/docs/configuration.md b/docs/configuration.md index 4db363e1b..ea4ff598b 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -27,6 +27,7 @@ This part of the configuration concerns anything that can affect the whole site. - `pageTitleSuffix`: a string added to the end of the page title. This only applies to the browser tab title, not the title shown at the top of the page. - `enableSPA`: whether to enable [[SPA Routing]] on your site. - `enablePopovers`: whether to enable [[popover previews]] on your site. +- `prefetch`: fetch pages before their links are followed, so they open at once ([[prefetching]]): `viewport` (default, links on screen and links pointed at), `hover` (only links pointed at) or `"off"`. Works with and without SPA routing. - `analytics`: what to use for analytics on your site. Values can be - `null`: don't use analytics; - `{ provider: 'google', tagId: '' }`: use Google Analytics; diff --git a/docs/features/SPA Routing.md b/docs/features/SPA Routing.md index d18aa2168..5acda696b 100644 --- a/docs/features/SPA Routing.md +++ b/docs/features/SPA Routing.md @@ -11,3 +11,5 @@ Under the hood, this is done by hijacking page navigations and instead fetching ## Configuration - Disable SPA Routing: set the `enableSPA` field of the [[configuration]] in `quartz.config.yaml` to be `false`. + +Pages are fetched ahead of a click by [[prefetching]], which the router uses to show them at once. diff --git a/docs/features/prefetching.md b/docs/features/prefetching.md new file mode 100644 index 000000000..a05fa6896 --- /dev/null +++ b/docs/features/prefetching.md @@ -0,0 +1,32 @@ +--- +title: Prefetching +tags: + - feature +--- + +Quartz fetches the pages a reader is likely to open next before they click, so following a link shows the page at once instead of waiting for the network. It works with and without [[SPA Routing]]. + +## How it works + +- **`viewport`** (the default): links on screen are fetched while the browser is idle, two at a time and at most 30 per page view. Pointing at a link or focusing it with the keyboard fetches it first, and touching it on a phone fetches it immediately. +- **`hover`**: only links that are pointed at for a moment, focused or touched are fetched. + +With [[SPA Routing]], Quartz keeps the fetched pages in memory for five minutes (at most 40 of them), and both page navigation and [[popover previews]] use them, so a page is never downloaded twice. Without SPA routing every link is a normal page load, so Quartz asks the browser to prefetch instead: with [Speculation Rules](https://developer.mozilla.org/en-US/docs/Web/API/Speculation_Rules_API) where the browser supports them, otherwise with ``. + +Quartz never prefetches: + +- links to other sites, links that open in a new tab, and downloads; +- links to files such as images and PDFs (only pages); +- with `viewport`, links on screen to pages that aren't in the site's content index (so a broken link in your layout doesn't show up as a 404 on every page); +- anything but links the reader points at, when the browser asks to save data (Data Saver) or the connection is 2G. + +To exclude a single link, add `data-no-prefetch` to it in HTML. Links with `data-router-ignore` are never prefetched either. + +## Configuration + +Set `prefetch` in the [[configuration]] in `quartz.config.yaml`: + +```yaml title="quartz.config.yaml" +configuration: + prefetch: viewport # or hover, or "off" +``` diff --git a/globals.d.ts b/globals.d.ts index 6cf30f8a1..c1a0ecd8e 100644 --- a/globals.d.ts +++ b/globals.d.ts @@ -10,8 +10,27 @@ export declare global { ): void dispatchEvent(ev: CustomEventMap[K] | UIEvent): void } + /** A page fetched ahead by prefetch.inline.ts (`url` is where it came from, after redirects). */ + interface PrefetchedPage { + url: string + contentType: string + /** The HTML; missing when the link turned out not to be a page. */ + text?: string + } interface Window { spaNavigate(url: URL, isBack: boolean = false) addCleanup(fn: (...args: any[]) => void) + /** + * Set when prefetching is on: the page at `url` from the prefetch cache, or fetched now and + * kept (undefined if it could not be fetched). + */ + quartzPrefetch?: { + load(url: URL): Promise + } + /** Absolute URL of the site's static/ folder (renderPage.tsx) */ + quartzStaticUrl?: string + /** Prefetch settings, written by componentResources.ts ahead of prefetch.inline.ts */ + __quartzPrefetchMode?: "viewport" | "hover" + __quartzSpa?: boolean } } diff --git a/quartz.config.default.yaml b/quartz.config.default.yaml index 626932d09..6610700b2 100644 --- a/quartz.config.default.yaml +++ b/quartz.config.default.yaml @@ -4,6 +4,7 @@ configuration: pageTitleSuffix: "" enableSPA: true enablePopovers: true + prefetch: viewport analytics: provider: plausible locale: en-US diff --git a/quartz/cfg.ts b/quartz/cfg.ts index 91f0e2eee..4ac1f9ec3 100644 --- a/quartz/cfg.ts +++ b/quartz/cfg.ts @@ -68,6 +68,12 @@ export interface GlobalConfiguration { enableSPA: boolean /** Whether to display Wikipedia-style popovers when hovering over links */ enablePopovers: boolean + /** + * Fetch pages before their links are followed, so they open at once (works with and without + * SPA routing). `viewport` (default): links on screen, while the browser is idle, and links + * pointed at. `hover`: only links pointed at, focused or touched. `off`: never. + */ + prefetch?: "viewport" | "hover" | "off" /** Analytics mode */ analytics: Analytics /** Glob patterns to not search */ diff --git a/quartz/components/scripts/popover.inline.ts b/quartz/components/scripts/popover.inline.ts index 6ed081f90..1f61b054e 100644 --- a/quartz/components/scripts/popover.inline.ts +++ b/quartz/components/scripts/popover.inline.ts @@ -55,12 +55,16 @@ async function mouseEnterHandler( return } - const response = await fetchCanonical(targetUrl).catch((err) => { - console.error(err) - }) + // A page fetched ahead (prefetch.inline.ts) is used as is, instead of fetching it again. + const prefetched = await window.quartzPrefetch?.load(targetUrl) + const response = prefetched + ? undefined + : await fetchCanonical(targetUrl).catch((err) => { + console.error(err) + }) - if (!response) return - const rawContentType = response.headers.get("Content-Type") + if (!prefetched && !response) return + const rawContentType = prefetched?.contentType ?? response?.headers.get("Content-Type") if (!rawContentType) return const [contentType] = rawContentType.split(";") const [contentTypeCategory, typeInfo] = contentType.split("/") @@ -93,7 +97,7 @@ async function mouseEnterHandler( } break default: - const contents = await response.text() + const contents = prefetched ? (prefetched.text ?? "") : await response!.text() const html = p.parseFromString(contents, "text/html") normalizeRelativeURLs(html, targetUrl) // prepend all IDs inside popovers to prevent duplicates diff --git a/quartz/components/scripts/prefetch.inline.ts b/quartz/components/scripts/prefetch.inline.ts new file mode 100644 index 000000000..1318fc443 --- /dev/null +++ b/quartz/components/scripts/prefetch.inline.ts @@ -0,0 +1,265 @@ +import { fetchCanonical } from "./util" + +/** + * Prefetching: fetch the pages a reader is likely to open next, so following a link shows the + * page at once instead of waiting for the network. + * + * - `viewport` (default): links on screen are fetched while the browser is idle, a few at a + * time; pointing at or focusing a link fetches it first. + * - `hover`: only links pointed at (after a short pause), focused, or touched. + * + * With SPA routing the pages are kept here, and the router (spa.inline.ts) and popovers + * (popover.inline.ts) take them through `window.quartzPrefetch`. Without it, every link is a full + * page load, so the browser prefetches instead: Speculation Rules where supported, otherwise + * ``. Nothing is prefetched with Data Saver on or on a 2G connection, + * except links pointed at. + * + * The mode is set by componentResources.ts, which prepends `window.__quartzPrefetchMode = …`. + */ + +type Mode = "viewport" | "hover" + +/** How long a fetched page is used before it is fetched again. */ +const MAX_AGE_MS = 5 * 60 * 1000 +/** Pages kept in memory (the oldest go first). */ +const MAX_PAGES = 40 +/** Pages fetched at once from the viewport. */ +const CONCURRENCY = 2 +/** Pages fetched from the viewport per page view. */ +const VIEWPORT_BUDGET = 30 +/** Pointing at a link this long counts as intent (instant.page's figure). */ +const HOVER_DELAY_MS = 65 + +const mode: Mode = window.__quartzPrefetchMode === "hover" ? "hover" : "viewport" +const spa = window.__quartzSpa === true + +type Cached = { time: number; page: Promise } +const cache = new Map() +const requested = new Set() + +function keyOf(url: URL): string { + const u = new URL(url) + u.hash = "" + return u.toString() +} + +function constrained(): boolean { + const connection = ( + navigator as Navigator & { connection?: { saveData?: boolean; effectiveType?: string } } + ).connection + return !!connection?.saveData || /(^|-)2g$/.test(connection?.effectiveType ?? "") +} + +/** A same-site page link worth fetching ahead, or undefined. */ +function targetOf(a: HTMLAnchorElement): URL | undefined { + if (!a.href || a.target === "_blank" || a.hasAttribute("download")) return + if ("routerIgnore" in a.dataset || "noPrefetch" in a.dataset) return + let url: URL + try { + url = new URL(a.href) + } catch { + return + } + if (url.origin !== window.location.origin || !/^https?:$/.test(url.protocol)) return + if (url.pathname === window.location.pathname && url.search === window.location.search) return + // pages have no extension (or .html); a link to an image, PDF or file is not worth the bytes + const last = url.pathname.split("/").pop() ?? "" + if (/\.[A-Za-z0-9]+$/.test(last) && !/\.html?$/i.test(last)) return + return url +} + +async function load(url: URL, priority: "low" | "high"): Promise { + try { + const res = await fetchCanonical(url, { priority } as RequestInit) + if (!res.ok) return undefined + const contentType = res.headers.get("content-type") ?? "" + if (!contentType.startsWith("text/html")) { + await res.body?.cancel() + return { url: res.url || url.toString(), contentType } + } + return { url: res.url || url.toString(), contentType, text: await res.text() } + } catch { + return undefined + } +} + +function remember(url: URL, priority: "low" | "high" = "low"): Promise { + const key = keyOf(url) + const hit = cache.get(key) + if (hit && Date.now() - hit.time < MAX_AGE_MS) return hit.page + const page = load(url, priority) + cache.set(key, { time: Date.now(), page }) + // a failed fetch is not kept, so following the link fetches it normally + page.then((p) => p === undefined && cache.get(key)?.page === page && cache.delete(key)) + while (cache.size > MAX_PAGES) cache.delete(cache.keys().next().value!) + return page +} + +const supportsSpeculationRules = + typeof HTMLScriptElement !== "undefined" && + typeof HTMLScriptElement.supports === "function" && + HTMLScriptElement.supports("speculationrules") + +/** Without SPA routing: ask the browser to prefetch the page for the navigation. */ +function hintBrowser(url: URL) { + const key = keyOf(url) + if (requested.has(key)) return + requested.add(key) + if (supportsSpeculationRules) { + const script = document.createElement("script") + script.type = "speculationrules" + script.textContent = JSON.stringify({ prefetch: [{ source: "list", urls: [key] }] }) + document.head.appendChild(script) + } else { + const link = document.createElement("link") + link.rel = "prefetch" + link.href = key + link.setAttribute("as", "document") + document.head.appendChild(link) + } +} + +function prefetch(url: URL) { + if (spa) void remember(url) + else hintBrowser(url) +} + +window.quartzPrefetch = { + // The page from the cache, or fetched now and kept: whoever asks first (a popover on + // mouseenter, the prefetcher after its hover delay, the router on click) fetches it once. + load: (url: URL) => remember(url, "high"), +} + +// --- intent: pointing at, focusing or touching a link ------------------------------------- + +let hoverTimer: ReturnType | undefined +const anchorOf = (target: EventTarget | null) => + target instanceof Element ? target.closest("a") : null + +document.addEventListener( + "pointerover", + (event) => { + const a = anchorOf(event.target) + const url = a && targetOf(a) + if (!url) return + clearTimeout(hoverTimer) + hoverTimer = setTimeout(() => prefetch(url), HOVER_DELAY_MS) + }, + { passive: true }, +) +document.addEventListener( + "pointerout", + (event) => { + if (anchorOf(event.target)) clearTimeout(hoverTimer) + }, + { passive: true }, +) +for (const type of ["pointerdown", "focusin"] as const) { + document.addEventListener( + type, + (event) => { + const a = anchorOf(event.target) + const url = a && targetOf(a) + if (url) prefetch(url) + }, + { passive: true }, + ) +} + +// --- viewport: links on screen, while the browser is idle -------------------------------- + +const idle = (fn: () => void) => + "requestIdleCallback" in window + ? window.requestIdleCallback(fn, { timeout: 2000 }) + : setTimeout(fn, 200) + +let observer: IntersectionObserver | undefined +let queue: URL[] = [] +let active = 0 +let budget = VIEWPORT_BUDGET + +function pump() { + while (active < CONCURRENCY && queue.length > 0 && budget > 0) { + const url = queue.shift()! + if (cache.has(keyOf(url)) || requested.has(keyOf(url))) continue + budget-- + active++ + idle(() => { + if (spa) { + remember(url).finally(() => { + active-- + pump() + }) + } else { + hintBrowser(url) + active-- + pump() + } + }) + } +} + +// Links on screen are fetched only when they name a page the site has (the content index, plus +// the folder and tag pages it doesn't list): a link in a layout to a page that doesn't exist +// would otherwise log a 404 on every page view. Without a content index, any link counts. +let known: Set | undefined +const knownReady: Promise = ( + typeof fetchData === "undefined" ? Promise.resolve({}) : fetchData +).then((index) => { + const slugs = Object.keys(index ?? {}) + if (slugs.length > 0) known = new Set(slugs) +}) + +function isKnownPage(url: URL): boolean { + if (!known) return true + const root = window.quartzStaticUrl ? new URL("..", window.quartzStaticUrl).pathname : "/" + if (!url.pathname.startsWith(root)) return false + let slug: string + try { + slug = decodeURI(url.pathname.slice(root.length)).replace(/\.html?$/i, "") + } catch { + return false + } + if (slug === "" || slug.endsWith("/")) slug += "index" + return known.has(slug) || slug.endsWith("index") || slug.startsWith("tags/") +} + +let observed = new WeakSet() +let queued = new Set() + +/** Watch the links on the page not watched yet (components may add theirs after `nav`). */ +function scan() { + if (!observer) return + for (const a of document.querySelectorAll("a[href]")) { + if (observed.has(a)) continue + observed.add(a) + if (targetOf(a)) observer.observe(a) + } +} + +function watchViewport() { + observer?.disconnect() + observer = undefined + queue = [] + queued = new Set() + observed = new WeakSet() + budget = VIEWPORT_BUDGET + if (mode !== "viewport" || constrained() || !("IntersectionObserver" in window)) return + observer = new IntersectionObserver((entries) => { + for (const entry of entries) { + if (!entry.isIntersecting) continue + observer?.unobserve(entry.target) + const url = targetOf(entry.target as HTMLAnchorElement) + if (!url || !isKnownPage(url) || queued.has(keyOf(url))) continue + queued.add(keyOf(url)) + queue.push(url) + } + pump() + }) + // after the other `nav` handlers have rendered their links (explorer, backlinks, …) + idle(() => knownReady.then(scan)) +} + +// every page view (SPA navigations included) brings new links +document.addEventListener("nav", watchViewport) +document.addEventListener("render", () => idle(() => knownReady.then(scan))) diff --git a/quartz/components/scripts/spa.inline.ts b/quartz/components/scripts/spa.inline.ts index bceefbd58..944d2db30 100644 --- a/quartz/components/scripts/spa.inline.ts +++ b/quartz/components/scripts/spa.inline.ts @@ -72,22 +72,35 @@ async function _navigate(url: URL, isBack: boolean = false) { // canonical link) changes the base its relative links resolve against, and the address bar // should show it too. fetch() drops the #hash, so keep the requested one. let finalUrl = url - const contents = await fetchCanonical(url) - .then((res) => { - if (res.url) { - finalUrl = new URL(res.url) - finalUrl.hash = url.hash - } - const contentType = res.headers.get("content-type") - if (contentType?.startsWith("text/html")) { - return res.text() - } else { - window.location.assign(url) - } - }) - .catch(() => { - window.location.assign(url) - }) + // A page fetched ahead (prefetch.inline.ts) is shown at once; one still loading is awaited. + const prefetched = await window.quartzPrefetch?.load(url) + if (prefetched && prefetched.text === undefined) { + // not a page (e.g. a file served without an extension): let the browser open it + window.location.assign(url) + return + } + if (prefetched) { + finalUrl = new URL(prefetched.url) + finalUrl.hash = url.hash + } + const contents = prefetched + ? prefetched.text + : await fetchCanonical(url) + .then((res) => { + if (res.url) { + finalUrl = new URL(res.url) + finalUrl.hash = url.hash + } + const contentType = res.headers.get("content-type") + if (contentType?.startsWith("text/html")) { + return res.text() + } else { + window.location.assign(url) + } + }) + .catch(() => { + window.location.assign(url) + }) if (!contents) return diff --git a/quartz/components/scripts/util.ts b/quartz/components/scripts/util.ts index f71790104..9a0f042ea 100644 --- a/quartz/components/scripts/util.ts +++ b/quartz/components/scripts/util.ts @@ -32,8 +32,8 @@ export function removeAllChildren(node: HTMLElement) { // way less robust - we only care about our own generated redirects after all. const canonicalRegex = // -export async function fetchCanonical(url: URL): Promise { - const res = await fetch(`${url}`) +export async function fetchCanonical(url: URL, init?: RequestInit): Promise { + const res = await fetch(`${url}`, init) if (!res.headers.get("content-type")?.startsWith("text/html")) { return res } @@ -42,5 +42,5 @@ export async function fetchCanonical(url: URL): Promise { // to allow the caller to read it if it's was not a redirect const text = await res.clone().text() const [_, redirect] = text.match(canonicalRegex) ?? [] - return redirect ? fetch(`${new URL(redirect, url)}`) : res + return redirect ? fetch(`${new URL(redirect, url)}`, init) : res } diff --git a/quartz/plugins/emitters/componentResources.ts b/quartz/plugins/emitters/componentResources.ts index 6cce0de48..066b4b8d2 100644 --- a/quartz/plugins/emitters/componentResources.ts +++ b/quartz/plugins/emitters/componentResources.ts @@ -7,6 +7,8 @@ import { emitStaticAssets } from "./staticAssets" import spaRouterScript from "../../components/scripts/spa.inline" // @ts-ignore import popoverScript from "../../components/scripts/popover.inline" +// @ts-ignore +import prefetchScript from "../../components/scripts/prefetch.inline" import baseStyles from "../../styles/base.scss" import customStyles from "../../styles/custom.scss" import popoverStyle from "../../components/styles/popover.scss" @@ -270,6 +272,18 @@ function addGlobalPageResources(ctx: BuildCtx, componentResources: ComponentReso `) } + // Prefetching (before the router or the no-SPA shim: both dispatch the first `nav`). Its + // settings lead the same script, since the other scripts load in parallel. + // (`prefetch: false` in YAML means off as well) + const prefetch = (cfg.prefetch as unknown) === false ? "off" : (cfg.prefetch ?? "viewport") + if (prefetch !== "off") { + componentResources.afterDOMLoaded.push( + `window.__quartzPrefetchMode = ${js(prefetch)};\n` + + `window.__quartzSpa = ${cfg.enableSPA ? "true" : "false"};\n` + + prefetchScript, + ) + } + if (cfg.enableSPA) { componentResources.afterDOMLoaded.push(spaRouterScript) } else { diff --git a/quartz/plugins/quartz-plugins.schema.json b/quartz/plugins/quartz-plugins.schema.json index cfd412d71..83d54d802 100644 --- a/quartz/plugins/quartz-plugins.schema.json +++ b/quartz/plugins/quartz-plugins.schema.json @@ -31,6 +31,12 @@ "type": "boolean", "description": "Enable hover popovers for links" }, + "prefetch": { + "type": "string", + "enum": ["viewport", "hover", "off"], + "default": "viewport", + "description": "Fetch pages before their links are followed: links on screen and pointed at (viewport), only links pointed at (hover), or never (off)" + }, "locale": { "type": "string", "description": "Locale code for the site"