Hago webs de oficio y hay cosas que copio de un proyecto a otro desde hace años. Las he juntado aquí: recetas sin librerías, herramientas que abro cada semana y todos mis enlaces de JavaScript, ordenados.
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.
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. */exportfunction 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`;// }));
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.
*/exportfunction 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. */exportconst 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();// }
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.
*/exportasyncfunction 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) thrownew 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;// }
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.
*/exportasyncfunction 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". */exportfunction nextClick(el) {
const { promise, resolve } = Promise.withResolvers();
el.addEventListener("click", resolve, { once: true });
return promise;
}
// await nextClick(okButton);
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.
*/exportfunction 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");
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.
*/exportfunction 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();// });
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.
*/exportfunction 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 });
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.
*/exportfunction 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]"));
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.
*/exportfunction 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;// });
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.
*/exportfunction 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()));
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.
*/exportfunction 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();
returnnew 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().
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.
*/exportasyncfunction copyText(text) {
try {
await navigator.clipboard.writeText(text);
returntrue;
} catch {
returnfalse;
}
}
// button.addEventListener("click", async () => {// const ok = await copyText(code.textContent);// button.textContent = ok ? "Copied" : "Copy failed";// });
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.
*/exportfunction readParams() {
return Object.fromEntries(new URL(location.href).searchParams);
}
exportfunction 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();
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.
*/exportfunction formToObject(form) {
const data = new FormData(form);
const out = {};
for (const key ofnew 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) });// });
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.
*/exportfunction copyState(state) {
return structuredClone(state);
}
// const draft = structuredClone(saved);// draft.items.push(newItem); // saved is untouched
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. */exportfunction byYear(posts) {
return Object.groupBy(posts, (post) => new Date(post.date).getFullYear());
}
/* Map.groupBy when the keys aren't strings, or the order matters. */exportfunction byLength(words) {
return Map.groupBy(words, (w) => w.length);
}
// byYear([{ date: "2025-03-01" }, { date: "2026-10-17" }])// → { 2025: [ … ], 2026: [ … ] }
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).
*/exportfunction 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),
};
}
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.
*/exportconst 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));
returntrue;
} catch {
returnfalse;
}
},
remove(key) {
try {
localStorage.removeItem(key);
} catch {}
},
};
// const prefs = store.get("prefs", { theme: "dark" });
«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. */exportfunction 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");
}
exportconst euros = (n, lang = navigator.language) =>
new Intl.NumberFormat(lang, { style: "currency", currency: "EUR" }).format(n);
exportconst compact = (n, lang = navigator.language) =>
new Intl.NumberFormat(lang, { notation: "compact" }).format(n);
exportconst 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"
fetch con tiempo límitefetch 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.
View TransitionsAnima 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.
Quitar listeners con una señalPasa el mismo signal a varios addEventListener y con un abort() se van todos. Adiós a guardar cada función para quitarla.
Fechas, números y listas con Intl«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.