Web Platformintermediate
export const parseValidUrls = (candidates: string[], base?: string): URL[] =>
candidates.filter((candidate) => URL.canParse(candidate, base)).map((candidate) => new URL(candidate, base));
export const isSameOriginRedirect = (target: string, currentOrigin: string): boolean => {
if (!URL.canParse(target, currentOrigin)) return false;
Validate URLs before you build or parse them with the built-in URL API.
Web Platformintermediate
type RvfcVideo = HTMLVideoElement & {
requestVideoFrameCallback: (cb: (now: number, meta: { mediaTime: number }) => void) => number;
cancelVideoFrameCallback: (handle: number) => void;
};
Schedule visual work with the browser's video frame callback for smoother rendering.
Web Platformintermediate
export const ensurePersistentStorage = async (): Promise<boolean> => {
if (!navigator.storage?.persist) return false;
if (await navigator.storage.persisted()) return true;
return navigator.storage.persist();
};
Ask the browser for persistent storage so your app can keep data around longer.
Web Platformintermediate
export const gzipEncode = async (text: string): Promise<Uint8Array> => {
const stream = new Blob([text]).stream().pipeThrough(new CompressionStream("gzip"));
const buffer = await new Response(stream).arrayBuffer();
return new Uint8Array(buffer);
};
Compress and decompress data in the browser with native Web Streams APIs.
Web Platformintermediate
@keyframes grow-progress {
to { transform: scaleX(1); }
}
.scroll-progress {
Tie CSS animations to scroll progress with the animation-timeline API.
Web Platformadvanced
const { port1, port2 } = new MessageChannel();
port2.onmessage = (event: MessageEvent<ArrayBuffer>) => {
console.log("received", event.data.byteLength, "bytes, zero-copy");
};
Passing an ArrayBuffer in postMessage's transfer list hands off ownership instead of cloning it — the sender's reference goes to byteLength 0.
Web Platformintermediate
export const pauseWhenHidden = (start: () => () => void) => {
let stop = start();
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") {
Stop polling, ticking, or rendering the instant a tab goes to the background, and resume with the same start function when it comes back.
Web Platformadvanced
const CACHE_NAME = "api-cache-v1";
export const fetchWithCache = async (url: string, maxAgeMs: number) => {
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(url);
Cache real Response objects by URL from plain page scripts, with a manual max-age check, no service worker required.
Web Platformadvanced
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
export const truncateGraphemes = (text: string, maxLength: number) => {
const graphemes = Array.from(segmenter.segment(text), (s) => s.segment);
if (graphemes.length <= maxLength) return text;
Truncate user text to N visible characters without splitting a multi-codepoint emoji or accented letter in half.
Web Platformintermediate
type IdleCallback = (deadline: IdleDeadline) => void;
const runOnNextTick = (callback: IdleCallback) => {
const start = performance.now();
setTimeout(() => callback({ didTimeout: false, timeRemaining: () => Math.max(0, 50 - (performance.now() - start)) }), 1);
Run analytics, prefetching, or cache warming only when the browser has real spare time, with a fallback for the one major browser that never shipped this API.
Web Platformadvanced
const CACHE_NAME = "app-shell-v1";
const PRECACHE_URLS = ["/", "/styles.css", "/app.js", "/offline.html"];
self.addEventListener("install", (event) => {
(event as Event & { waitUntil: (p: Promise<unknown>) => void }).waitUntil(
Precache the app shell on install and serve every request from cache first, falling back to the network only on a cache miss.
Web Platformadvanced
const dbPromise = new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open("app-cache", 1);
request.onupgradeneeded = () => request.result.createObjectStore("kv");
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
Turn IndexedDB's callback-and-event API into two functions, idbGet and idbSet, that behave like a normal async key-value store.
Web Platformintermediate
export const copyToClipboard = (text: string) =>
navigator.clipboard.writeText(text).then(() => true).catch(() => false);
export const pasteFromClipboard = () =>
navigator.clipboard.readText().then((text) => text).catch(() => null);
Copy text, read it back, and copy raw image data to the system clipboard with a promise-based API — no hidden textarea, no execCommand.
Web Platformintermediate
export const shareOrCopy = async (data: ShareData) => {
if (!navigator.canShare?.(data)) {
await navigator.clipboard.writeText(data.url ?? data.text ?? "");
return "copied";
}
Open the OS-native share sheet on a button click, and fall back to copying the link on browsers — Firefox desktop included — that don't support it.
Web Platformintermediate
.card-wrapper {
container: card / inline-size;
}
.card {
Let a card switch to a two-column layout based on its own wrapper's width, not the viewport, so it works the same in a sidebar or a full-width column.
Web Platformintermediate
.empty-state {
display: none;
}
.results:not(:has(li)) + .empty-state {
Style a table row from its checkbox and swap in an empty-state message when a list has no items, with zero JavaScript.
Web Platformintermediate
const channel = new BroadcastChannel("auth");
export const broadcastLogout = (reason: string) => channel.postMessage({ type: "logout", reason });
channel.addEventListener("message", (event: MessageEvent<{ type: string; reason: string }>) => {
Log out in one tab and every other open tab reacts instantly, with a plain publish/subscribe API and no polling or server round trip.
Web Platformadvanced
export const getFreshAuthToken = () =>
navigator.locks.request("auth-token-refresh", async () => {
const expiresAt = Number(localStorage.getItem("auth-token-expires-at") ?? 0);
if (Date.now() < expiresAt) return localStorage.getItem("auth-token")!;
Stop every open tab from refreshing the same auth token at once — let one tab do the network call while the rest wait and reuse its result.
Web Platformintermediate
const setLayout = (el: HTMLElement, width: number) => {
el.classList.toggle("is-wide", width >= 560);
el.classList.toggle("is-compact", width < 320);
};
Give a component its own width-based breakpoints, driven by its actual box size instead of the window's, with no global resize listener at all.
Web Platformintermediate
const observer = new IntersectionObserver((entries, obs) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const img = entry.target as HTMLImageElement;
img.src = img.dataset.src ?? "";
Load images only when they're about to enter the viewport, using one shared observer instead of a scroll listener per image.
Web Platformintermediate
const routeChangeController = new AbortController();
window.addEventListener("pagehide", () => routeChangeController.abort(), { once: true });
export const search = (query: string) => {
const requestController = new AbortController();
Cancel a fetch when any of several unrelated conditions fires — a timeout, a route change, an explicit cancel — without hand-rolling a signal merger.