js.joedoe.dev

recetas

Recetas

JavaScript del navegador, sin instalar nada, que acabo copiando de un proyecto a otro. Cada receta es un archivo: el código que ves es el mismo que corre al pulsar «Probar».

Tiempo y rendimiento#

Debounce#

Espera a que dejen de llamar para hacer el trabajo una sola vez. Lo uso en cada buscador que pinta resultados mientras escribes.

Lo que la IA suele hacer mal. Suele dar un debounce que pierde el this y los argumentos, o lo crea dentro del manejador del input, así que cada tecla estrena un temporizador nuevo y no espera a nada.

/* Runs fn once the calls stop for `wait` ms: search boxes, resize, autosave. */
export function debounce(fn, wait = 250) {
	let timer;
	return (...args) => {
		clearTimeout(timer);
		timer = setTimeout(() => fn(...args), wait);
	};
}

// const search = debounce((q) => fetchResults(q), 300);
// input.addEventListener("input", (e) => search(e.target.value));
src/recipes/debounce.js

Throttle con requestAnimationFrame#

Baseline: en todos los navegadoresMDN ↗

Como mucho una vez por fotograma, con los últimos datos. Para scroll y pointermove: más veces no se ven y solo cuestan.

Lo que la IA suele hacer mal. Te propone un throttle con setTimeout de 16 ms o el de lodash para el scroll. Va desacompasado con la pantalla; requestAnimationFrame ya es una vez por fotograma.

/* At most once per frame, with the latest arguments: scroll, pointermove. */
export function rafThrottle(fn) {
	let frame = 0;
	let last;
	return (...args) => {
		last = args;
		if (frame) return;
		frame = requestAnimationFrame(() => {
			frame = 0;
			fn(...last);
		});
	};
}

// window.addEventListener("pointermove", rafThrottle((e) => {
//   dot.style.translate = `${e.clientX}px ${e.clientY}px`;
// }));
src/recipes/throttle.js

Trabajo para cuando haya tiempo#

MDN ↗

requestIdleCallback para lo que puede esperar y ceder el hilo en bucles largos, para que los clics no se queden colgados.

Lo que la IA suele hacer mal. Mete el trabajo pesado en un setTimeout(…, 0) y da por hecho que ya no bloquea. Solo lo aplaza: el bucle largo sigue congelando los clics.

/*
 * Leave the work that can wait (analytics, prefetch, warming a cache) for
 * when the browser has nothing better to do. setTimeout where it's missing.
 */
export function whenIdle(task, timeout = 2000) {
	if ("requestIdleCallback" in window) {
		return requestIdleCallback(task, { timeout });
	}
	return setTimeout(() => task({ didTimeout: true, timeRemaining: () => 0 }), 1);
}

/* In a long loop, hand the main thread back now and then so clicks still land. */
export const yieldToMain = () =>
	globalThis.scheduler?.yield ? scheduler.yield() : new Promise((r) => setTimeout(r, 0));

// for (const item of bigList) {
//   process(item);
//   if (++n % 200 === 0) await yieldToMain();
// }
src/recipes/idle.js

Red#

fetch con tiempo límite#

MDN ↗

fetch no se rinde nunca por sí solo. AbortSignal.timeout le pone límite y AbortSignal.any lo junta con tu propio botón de cancelar.

Lo que la IA suele hacer mal. Monta el tiempo límite con Promise.race y un setTimeout: la petición no se cancela, solo se deja de esperar, y sigue gastando red. Tampoco suele mirar res.ok.

/*
 * fetch that gives up after `ms`, and that you can also cancel yourself.
 * AbortSignal.any joins both: whichever fires first wins.
 */
export async function getJSON(url, { ms = 8000, signal } = {}) {
	const timeout = AbortSignal.timeout(ms);
	const res = await fetch(url, {
		signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
	});
	if (!res.ok) throw new Error(`HTTP ${res.status}`);
	return res.json();
}

// try {
//   const data = await getJSON("/api/things", { ms: 3000 });
// } catch (err) {
//   if (err.name === "TimeoutError") showRetry();   // too slow
//   else if (err.name === "AbortError") {}          // we cancelled it
//   else throw err;
// }
src/recipes/fetch-timeout.js

Varias promesas a la vez#

MDN ↗

allSettled para quedarte con lo que funcionó aunque algo falle, y withResolvers para una promesa que resuelves desde fuera.

Lo que la IA suele hacer mal. Pone un await detrás de otro para cosas que no dependen entre sí, o usa Promise.all donde un solo fallo tira por la borda todo lo que sí salió bien.

/*
 * allSettled: run everything, keep what worked, list what failed,
 * instead of Promise.all throwing away all of it at the first error.
 */
export async function loadAll(urls) {
	const results = await Promise.allSettled(urls.map((u) => fetch(u).then((r) => r.json())));
	return {
		ok: results.filter((r) => r.status === "fulfilled").map((r) => r.value),
		failed: results.flatMap((r, i) => (r.status === "rejected" ? [urls[i]] : [])),
	};
}

/* withResolvers: a promise you resolve from outside, e.g. "wait for this click". */
export function nextClick(el) {
	const { promise, resolve } = Promise.withResolvers();
	el.addEventListener("click", resolve, { once: true });
	return promise;
}

// await nextClick(okButton);
src/recipes/promises.js

Hablar entre pestañas#

Baseline: en todos los navegadoresMDN ↗

BroadcastChannel: cerrar sesión en todas las pestañas a la vez o parar la música de una cuando empieza en otra.

Lo que la IA suele hacer mal. Tira del evento storage de localStorage para avisar a las otras pestañas: escribe en disco para mandar un mensaje y no llega a la pestaña que lo envía.

/*
 * Talk between tabs of the same site: log out everywhere, sync a cart,
 * stop a player when another tab starts one. Same name, same channel.
 */
export function channel(name, onMessage) {
	const bc = new BroadcastChannel(name);
	bc.addEventListener("message", (event) => onMessage(event.data));
	return {
		send: (data) => bc.postMessage(data),
		close: () => bc.close(),
	};
}

// const session = channel("session", (msg) => msg === "logout" && location.reload());
// logoutButton.onclick = () => session.send("logout");
src/recipes/broadcast.js

DOM y eventos#

Delegación de eventos#

Baseline: en todos los navegadoresMDN ↗

Un solo listener en el padre en lugar de uno por botón. Sirve también para lo que añadas después.

Lo que la IA suele hacer mal. Pone un addEventListener en cada elemento de la lista dentro de un forEach, y los que se añaden después se quedan sin oyente. O compara e.target sin closest() y falla al pulsar el icono de dentro.

/*
 * One listener on the parent instead of one per button. Works for items
 * added later, too. closest() finds the button even if you click its icon.
 */
export function delegate(root, type, selector, handler) {
	const listener = (event) => {
		const match = event.target.closest(selector);
		if (match && root.contains(match)) handler(event, match);
	};
	root.addEventListener(type, listener);
	return () => root.removeEventListener(type, listener);
}

// delegate(list, "click", "[data-remove]", (event, button) => {
//   button.closest("li").remove();
// });
src/recipes/delegation.js

Quitar listeners con una señal#

Baseline: en todos los navegadoresMDN ↗

Pasa el mismo signal a varios addEventListener y con un abort() se van todos. Adiós a guardar cada función para quitarla.

Lo que la IA suele hacer mal. Pasa una función flecha a addEventListener y luego otra flecha «igual» a removeEventListener: no es la misma función, así que no quita nada.

/*
 * Remove a whole bunch of listeners at once: give them the same signal and
 * abort it. No need to keep references to every handler.
 */
export function bindDrag(el, onMove) {
	const controller = new AbortController();
	const { signal } = controller;
	el.addEventListener("pointerdown", () => {
		window.addEventListener("pointermove", onMove, { signal });
		window.addEventListener("pointerup", () => controller.abort(), { once: true, signal });
	}, { once: true, signal });
	return () => controller.abort();
}

// { once: true } alone removes a listener after its first call:
// dialog.addEventListener("close", cleanUp, { once: true });
src/recipes/listeners-signal.js

Aparecer al entrar en pantalla#

Baseline: en todos los navegadoresMDN ↗

IntersectionObserver marca lo que entra en pantalla y deja de vigilarlo. El mismo patrón sirve para cargar imágenes o vídeos tarde.

Lo que la IA suele hacer mal. Escucha el scroll y llama a getBoundingClientRect en cada evento, lo que fuerza a recalcular la página decenas de veces por segundo. Y no deja de observar lo que ya apareció.

/*
 * Adds .is-in when an element enters the screen, once, and stops watching it.
 * Same pattern for lazy anything: swap data-src for src inside the callback.
 */
export function reveal(elements, { rootMargin = "0px 0px -10% 0px" } = {}) {
	const io = new IntersectionObserver(
		(entries) => {
			for (const entry of entries) {
				if (!entry.isIntersecting) continue;
				entry.target.classList.add("is-in");
				io.unobserve(entry.target);
			}
		},
		{ rootMargin },
	);
	for (const el of elements) io.observe(el);
	return () => io.disconnect();
}

// reveal(document.querySelectorAll("[data-reveal]"));
src/recipes/reveal.js

El tamaño de un elemento#

Baseline: en todos los navegadoresMDN ↗

ResizeObserver avisa cuando cambia el tamaño de una caja, no de la ventana. Para canvas y gráficos que tienen que redibujarse.

Lo que la IA suele hacer mal. Escucha el resize de window para saber cuánto mide un elemento. No se entera cuando cambia por su contenido o por una barra lateral, solo cuando cambia la ventana.

/*
 * Calls back with an element's own size whenever it changes, not the
 * window's. For canvases, charts, or anything a container query can't do.
 */
export function onResize(el, callback) {
	const ro = new ResizeObserver(([entry]) => {
		const { inlineSize: width, blockSize: height } = entry.contentBoxSize[0];
		callback({ width, height });
	});
	ro.observe(el);
	return () => ro.disconnect();
}

// onResize(canvas.parentElement, ({ width, height }) => {
//   canvas.width = width * devicePixelRatio;
//   canvas.height = height * devicePixelRatio;
// });
src/recipes/resize.js

Interfaz#

View Transitions#

Baseline: recienteMDN ↗

Anima cualquier cambio del DOM: el navegador hace una foto antes y otra después y las funde. Sin soporte o con movimiento reducido, cambia sin más.

Lo que la IA suele hacer mal. Llama a document.startViewTransition sin comprobar que exista, y en Firefox antiguo la página se rompe. Tampoco suele respetar prefers-reduced-motion.

/*
 * Animates any DOM change: the browser snapshots before and after and
 * crossfades. Without support, or with reduced motion, it just changes.
 */
export function transition(update) {
	const calm = matchMedia("(prefers-reduced-motion: reduce)").matches;
	if (!document.startViewTransition || calm) {
		update();
		return Promise.resolve();
	}
	return document.startViewTransition(update).finished;
}

// Give each moving item its own name and they glide to their new place:
// li.style.viewTransitionName = `item-${id}`;
// transition(() => list.append(...[...list.children].reverse()));
src/recipes/view-transition.js

Respetar el movimiento reducido#

Baseline: en todos los navegadoresMDN ↗

En CSS hay media query; en JS hace falta matchMedia, y escuchar el cambio, porque hay quien lo activa a mitad de visita.

Lo que la IA suele hacer mal. Lee matchMedia(…).matches una vez al cargar y ya. Si la persona cambia el ajuste con la página abierta, no se entera.

/*
 * Ask before animating from script. CSS has its media query; JS needs
 * matchMedia, and the change event, because people switch it mid-visit.
 */
const query = matchMedia("(prefers-reduced-motion: reduce)");

export const prefersCalm = () => query.matches;

export function onMotionChange(callback) {
	const listener = () => callback(query.matches);
	query.addEventListener("change", listener);
	return () => query.removeEventListener("change", listener);
}

// el.animate(frames, { duration: prefersCalm() ? 0 : 600 });
src/recipes/reduced-motion.js

Un confirm() con <dialog>#

Baseline: en todos los navegadoresMDN ↗

Un <dialog> de verdad trae el foco atrapado, Esc y el fondo sin escribir nada. Lo envuelvo en una promesa y queda como un confirm() bonito.

Lo que la IA suele hacer mal. Te monta un modal con un div, un fondo y z-index: 9999. Sin <dialog> no hay foco atrapado, ni Esc, ni el resto de la página inerte.

/*
 * A confirm() that looks like your site: a real <dialog> with focus trap,
 * Esc and the backdrop for free. Resolves with the button's value.
 */
export function ask(message, { yes = "OK", no = "Cancel" } = {}) {
	const dialog = document.createElement("dialog");
	const form = document.createElement("form");
	form.method = "dialog";
	const text = document.createElement("p");
	text.textContent = message;
	const cancel = Object.assign(document.createElement("button"), { value: "no", textContent: no });
	const accept = Object.assign(document.createElement("button"), { value: "yes", textContent: yes });
	form.append(text, cancel, accept);
	dialog.append(form);
	document.body.append(dialog);
	dialog.showModal();
	return new Promise((resolve) => {
		dialog.addEventListener("close", () => {
			resolve(dialog.returnValue === "yes");
			dialog.remove();
		}, { once: true });
	});
}

// Lighter menus and tips need no JS at all: popover="auto" + popovertarget.
// From script: menu.showPopover(), menu.hidePopover(), menu.togglePopover().
src/recipes/dialog.js

Botón de copiar#

Baseline: en todos los navegadoresMDN ↗

navigator.clipboard necesita https y un gesto de quien visita. Devuelvo si ha ido bien para que el botón no mienta.

Lo que la IA suele hacer mal. Aún tira de document.execCommand('copy') con un textarea escondido, que está obsoleto. O usa navigator.clipboard sin catch, y si falla el botón se queda mudo.

/*
 * The copy button. Needs https (or localhost) and a click or key press;
 * it says whether it worked so the button can tell the truth.
 */
export async function copyText(text) {
	try {
		await navigator.clipboard.writeText(text);
		return true;
	} catch {
		return false;
	}
}

// button.addEventListener("click", async () => {
//   const ok = await copyText(code.textContent);
//   button.textContent = ok ? "Copied" : "Copy failed";
// });
src/recipes/clipboard.js

Datos y estado#

Filtros en la URL#

Baseline: en todos los navegadoresMDN ↗

Guarda la búsqueda en la barra de direcciones: recargar o compartir el enlace abre lo mismo. replaceState para no llenar el historial.

Lo que la IA suele hacer mal. Arma la query string a mano, concatenando, sin encodeURIComponent: un «&» en el filtro la rompe. Y usa pushState en cada tecla, llenando el historial.

/*
 * Keep filters in the address bar, so a reload or a shared link opens the
 * same view. replaceState: no new history entry per keystroke.
 */
export function readParams() {
	return Object.fromEntries(new URL(location.href).searchParams);
}

export function setParam(key, value) {
	const url = new URL(location.href);
	if (value === "" || value == null) url.searchParams.delete(key);
	else url.searchParams.set(key, value);
	history.replaceState(null, "", url);
}

// setParam("q", input.value);   // ?q=gsap
// const { q = "" } = readParams();
src/recipes/url-params.js

Un formulario a objeto#

Baseline: en todos los navegadoresMDN ↗

FormData lee todo el formulario de una vez, sin ir campo a campo. Las casillas repetidas salen como lista.

Lo que la IA suele hacer mal. Lee cada campo con un querySelector(…).value, uno por línea, y se olvida de los checkbox desmarcados y de los select múltiples.

/*
 * A form straight into an object, no field-by-field. Checkbox groups and
 * multiple selects come back as arrays thanks to getAll.
 */
export function formToObject(form) {
	const data = new FormData(form);
	const out = {};
	for (const key of new Set(data.keys())) {
		const values = data.getAll(key);
		out[key] = values.length > 1 ? values : values[0];
	}
	return out;
}

// form.addEventListener("submit", async (e) => {
//   e.preventDefault();
//   await fetch(form.action, { method: "POST", body: new FormData(form) });
// });
src/recipes/form-data.js

Copia profunda#

Baseline: en todos los navegadoresMDN ↗

structuredClone copia de verdad y, a diferencia del truco de JSON, conserva fechas, Map, Set y referencias circulares.

Lo que la IA suele hacer mal. Casi siempre propone JSON.parse(JSON.stringify(x)): las fechas vuelven como texto y los Map, Set y undefined desaparecen sin avisar.

/*
 * A real deep copy, built in. Unlike JSON.parse(JSON.stringify(x)) it keeps
 * Dates, Maps, Sets, typed arrays and circular references.
 * It can't copy functions, DOM nodes or class instances' methods.
 */
export function copyState(state) {
	return structuredClone(state);
}

// const draft = structuredClone(saved);
// draft.items.push(newItem);   // saved is untouched
src/recipes/structured-clone.js

Agrupar con Object.groupBy#

MDN ↗

El reduce que escribía a mano cada semana, ahora de serie. Map.groupBy cuando las claves no son texto.

Lo que la IA suele hacer mal. Escribe un reduce de seis líneas con el acumulador inicializado a mano, o importa groupBy de lodash, cuando Object.groupBy ya está en todos los navegadores.

/* Object.groupBy: the reduce I used to write by hand every week. */
export function byYear(posts) {
	return Object.groupBy(posts, (post) => new Date(post.date).getFullYear());
}

/* Map.groupBy when the keys aren't strings, or the order matters. */
export function byLength(words) {
	return Map.groupBy(words, (w) => w.length);
}

// byYear([{ date: "2025-03-01" }, { date: "2026-10-17" }])
// → { 2025: [ … ], 2026: [ … ] }
src/recipes/group-by.js

Arrays sin mutar#

Baseline: en todos los navegadoresMDN ↗

toSorted, toReversed, with y toSpliced devuelven una copia. Perfectos para estado que no se puede tocar, como en Vue o en un deshacer.

Lo que la IA suele hacer mal. Llama a sort() o reverse() sobre el array del estado para pintar una lista ordenada: lo cambia en su sitio y el original queda tocado.

/*
 * The array methods that return a new array instead of changing the old one.
 * Good with state you must not mutate (Vue, React, undo history).
 */
export function arrays(list) {
	return {
		sorted: list.toSorted((a, b) => a - b),   // sort() without touching list
		reversed: list.toReversed(),
		replaced: list.with(0, 99),               // list[0] = 99, as a copy
		removed: list.toSpliced(1, 1),
		last: list.at(-1),                        // no more list[list.length - 1]
		lastBig: list.findLast((n) => n > 2),
	};
}
src/recipes/arrays.js

localStorage sin sustos#

Baseline: en todos los navegadoresMDN ↗

localStorage puede lanzar errores (modo privado, lleno, cookies bloqueadas) y solo guarda texto. Envuelto una vez, el resto del código deja de preocuparse.

Lo que la IA suele hacer mal. Hace JSON.parse(localStorage.getItem(…)) a pelo: un valor corrupto o el modo privado de Safari lanzan una excepción y la app no arranca.

/*
 * localStorage can throw (private mode, full, blocked cookies) and only
 * holds strings. Wrapped once, the rest of the code stops worrying.
 */
export const store = {
	get(key, fallback = null) {
		try {
			const raw = localStorage.getItem(key);
			return raw === null ? fallback : JSON.parse(raw);
		} catch {
			return fallback;
		}
	},
	set(key, value) {
		try {
			localStorage.setItem(key, JSON.stringify(value));
			return true;
		} catch {
			return false;
		}
	},
	remove(key) {
		try {
			localStorage.removeItem(key);
		} catch {}
	},
};

// const prefs = store.get("prefs", { theme: "dark" });
src/recipes/storage.js

Idiomas#

Fechas, números y listas con Intl#

Baseline: en todos los navegadoresMDN ↗

«Hace 3 días», «1,2 mil», «Vue, Svelte y Astro» en el idioma de quien visita y sin librería. Prueba la demo en las tres lenguas.

Lo que la IA suele hacer mal. Formatea fechas con getDate() + '/' + (getMonth() + 1) y números con toFixed(2) y un replace del punto. Sale en un solo idioma y mal en los demás.

/* Dates, numbers and lists in the visitor's language, no library. */

export function timeAgo(date, lang = navigator.language) {
	const rtf = new Intl.RelativeTimeFormat(lang, { numeric: "auto" });
	const seconds = (date.getTime() - Date.now()) / 1000;
	const steps = [
		["year", 31536000],
		["month", 2592000],
		["week", 604800],
		["day", 86400],
		["hour", 3600],
		["minute", 60],
	];
	for (const [unit, size] of steps) {
		if (Math.abs(seconds) >= size) return rtf.format(Math.round(seconds / size), unit);
	}
	return rtf.format(Math.round(seconds), "second");
}

export const euros = (n, lang = navigator.language) =>
	new Intl.NumberFormat(lang, { style: "currency", currency: "EUR" }).format(n);

export const compact = (n, lang = navigator.language) =>
	new Intl.NumberFormat(lang, { notation: "compact" }).format(n);

export const list = (items, lang = navigator.language) =>
	new Intl.ListFormat(lang, { type: "conjunction" }).format(items);

// timeAgo(new Date(Date.now() - 3 * 86400e3), "es")  → "hace 3 días"
// list(["Vue", "Svelte", "Astro"], "ca")             → "Vue, Svelte i Astro"
src/recipes/intl.js

↑↓ moverse · ↵ abrir · esc cerrar