# Reglas de Codificación con IA para el Rendimiento de Sitios Estáticos

> Reglas de AGENTS.md para el rendimiento de sitios estáticos que aplican Core Web Vitals, optimización de imágenes, carga de fuentes y evitan que los agentes envíen recursos que bloquean el renderizado.

**Type:** Rule  
**Tools:** Cursor, Claude Code, Codex, Windsurf  
**Stack:** Astro, Next.js, TypeScript, Tailwind  
**Updated:** 2026-06-08

---

Coloca esto en la raíz de tu repositorio como `AGENTS.md`. Las reglas de rendimiento son especialmente importantes para el código generado por IA porque los agentes optimizan para la corrección y rara vez consideran el tamaño del paquete, los recursos que bloquean el renderizado o el cambio de diseño sin instrucción explícita.

## AGENTS.md

```md title="AGENTS.md"
# Project Rules — Static Site Performance

## Core Web Vitals targets
- LCP (Largest Contentful Paint): < 2.5 s on a simulated 4G mobile connection.
- CLS (Cumulative Layout Shift): < 0.1. All images, ads, and embeds must have
  explicit `width` and `height` attributes (or `aspect-ratio` CSS) to reserve space.
- FID / INP (Interaction to Next Paint): < 200 ms. Minimise main-thread JavaScript.
- These are not aspirational — they are definition-of-done criteria for any page change.

## Images — highest impact
- Never use bare `<img>` tags. Use the framework's image component:
  - Astro: `<Image />` from `astro:assets`
  - Next.js: `<Image />` from `next/image`
- Serve images in WebP or AVIF. No JPEG/PNG without a `<picture>` element with
  a next-gen format source.
- Hero images (above the fold) must use `loading="eager"` and `fetchpriority="high"`.
  All other images use `loading="lazy"` (the default in the framework image components).
- Never inline large base64-encoded images in HTML or CSS. Images above 2 KB should
  be served as separate files and cached by the CDN.
- Always provide `alt` text. Decorative images use `alt=""`. Informational images
  describe their content in under 125 characters.

## Fonts
- Fonts must be self-hosted (from `public/fonts/` or via the framework's font module).
  Never load fonts from Google Fonts in production — it adds a cross-origin DNS lookup
  and blocks rendering on slow connections.
- Use `font-display: swap` in all `@font-face` declarations.
- Preload only the primary font file (the weight used for body text):
  `<link rel="preload" as="font" type="font/woff2" crossorigin>`.
  Preloading every weight defeats the purpose.
- Limit to 2 font families per site (e.g. one for headings, one for body). Every
  additional font family is an additional blocking resource.

## JavaScript — bundle discipline
- Every JS file added to the `<head>` must have `defer` or `async`. No synchronous
  scripts in `<head>` — they block HTML parsing.
- Third-party scripts (analytics, chat widgets, consent banners) must be loaded after
  the page is interactive. Use `type="module"` + dynamic `import()` or the framework's
  `client:idle` / `strategy="lazyOnload"` equivalents.
- Do not add a JavaScript dependency for something that can be done in CSS or HTML.
  Parallax, smooth scroll, sticky headers, and CSS animations do not need JavaScript.
- Run `bundlephobia.com` or check `npx bundlephobia <package>` before adding any
  new npm package. Document the gzipped size in the PR description.

## CSS
- Tailwind CSS purges unused classes at build time — this is the correct approach.
  Do not add a global CSS file that imports every utility class from a library.
- Never use `@import url(...)` inside a CSS file for non-local resources. This is
  a render-blocking network request.
- Critical above-the-fold CSS may be inlined in `<style>` in the `<head>`. Non-critical
  CSS must be loaded asynchronously (`rel="preload" as="style"` + `onload` swap trick
  or the framework's equivalent).

## HTML and document structure
- Set `<meta name="viewport" content="width=device-width, initial-scale=1">` on
  every page. Missing this causes mobile browsers to render at desktop width.
- Use `<link rel="preconnect">` for essential third-party origins (CDNs, API hosts)
  that are always needed on page load. Limit to 3 or fewer origins.
- Minify HTML output. Astro and Next.js do this by default — do not disable it.

## Definition of done
- `astro build` or `next build` completes without warnings.
- Lighthouse performance score ≥ 90 on mobile for any changed page.
- No `<img>` tags without `width`/`height` (CLS protection).
- No render-blocking `<script>` in `<head>`.
- `web-vitals` test (`npx unlighthouse --site localhost:4321`) shows LCP < 2.5 s.
```

## Por qué estas reglas

- **Imágenes con dimensiones explícitas (prevención de CLS)** es la regla de rendimiento más frecuentemente omitida en el código generado por IA. Los agentes que escriben `<img src="...">` sin los atributos `width` y `height` provocan que la página se refluya cuando la imagen se carga, produciendo puntuaciones de CLS que pueden hundir el ranking del sitio. La solución es mecánica — siempre proporcionar dimensiones — pero los agentes la omiten a menos que se les indique explícitamente.
- **Fuentes autoalojadas** elimina una solicitud de origen cruzado que bloquea el renderizado y que retrasa constantemente el LCP entre 200 y 400 ms en conexiones típicas. Los agentes recurren por defecto a las etiquetas `<link>` de Google Fonts por familiaridad — son adecuadas para desarrollo, pero son mensurablemente más lentas que las fuentes autoalojadas con `font-display: swap`.

## Buena opción

- Sitios estáticos orientados al público, páginas de marketing, blogs y documentación donde Core Web Vitals afectan directamente el ranking de búsqueda y la conversión de usuarios.

## No es adecuado

- Paneles internos o aplicaciones autenticadas donde los usuarios están en conexiones confiables y el ranking SEO es irrelevante — las restricciones de rendimiento son reales, pero el impacto empresarial es menor.