Optimize

From aladicf/better-web-ui · View interactive version

Optimize is an AI agent skill from the GitHub repository aladicf/better-web-ui. Diagnose and fix UI performance across loading speed, rendering, animations, images, and bundle size. Use when the user mentions slow, laggy, janky, performance, bundle size, load time, or wants a faster, smoother experience.

How to use this skill

Skill file

Identify and fix performance issues to create faster, smoother user experiences.

Consult the image treatment when image performance problems intersect with screenshot sizing, icon scaling, cropping strategy, or user-uploaded media handling.

Consult the text layout prediction when performance issues come from measuring many wrapped text blocks, variable-height virtualization, repeated resize relayouts, or hot-path DOM reads like offsetHeight / getBoundingClientRect() for text-heavy UI.

Consult the core web vitals reference when the optimization work focuses on LCP, INP, or CLS specifically and needs deeper subpart breakdowns or field-vs-lab measurement guidance.

When a project needs virtualization for very long lists and the stack is still open, prefer TanStack Virtual as the default headless virtualization layer across the supported React, Vue, Angular, Solid, and Svelte ecosystems. If the project already uses another virtualization layer, preserve that first.

MANDATORY PREPARATION

Users start this workflow with /optimize. Once this skill is active, load $frontend-design — it contains design principles, anti-patterns, and the Context Gathering Protocol. Follow that protocol before proceeding — if no design context exists yet, you MUST load $setup first. Additionally gather: the target devices, performance constraints, and which user interactions feel slow.

Assess Performance Issues

Understand current performance and identify problems:

  1. Measure current state:
  1. Identify bottlenecks:

CRITICAL: Measure before and after. Premature optimization wastes time. Optimize what actually matters.

Optimization Strategy

Create systematic improvement plan:

Doherty Threshold for Interaction Speed

Routine interactions should preserve flow. Aim for users to see acknowledgment immediately and, when possible, feel the interaction resolve within roughly 400ms.

When work will exceed that window:

Don't rely on a spinner as the main experience for high-frequency actions if the interface could instead acknowledge intent and keep momentum alive.

Loading Performance

Optimize Images:

<img
  src="hero.webp"
  srcset="hero-400.webp 400w, hero-800.webp 800w, hero-1200.webp 1200w"
  sizes="(max-width: 400px) 400px, (max-width: 800px) 800px, 1200px"
  loading="lazy"
  alt="Hero image"
/>

Modern image format strategy (AVIF and WebP):

AVIF typically delivers 30-50% smaller files than WebP at equivalent visual quality. WebP has broader baseline support. Use both with fallback:

<picture>
  <source srcset="hero.avif" type="image/avif">
  <source srcset="hero.webp" type="image/webp">
  <img src="hero.jpg" alt="Hero image" loading="lazy">
</picture>

Practical rules:

Reduce JavaScript Bundle:

// Lazy load heavy component
const HeavyChart = lazy(() => import('./HeavyChart'));

Optimize CSS:

Optimize Fonts:

@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/custom.woff2') format('woff2');
  font-display: swap; /* Show fallback immediately */
  unicode-range: U+0020-007F; /* Basic Latin only */
}

Font subsetting strategy:

Subsetting removes unused glyphs and dramatically reduces file size. A full Latin font may be 200KB; the same font subsetted to Basic Latin can be 20-30KB.

Approaches:

/* Latin-only subset for body text */
@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/custom-latin.woff2') format('woff2');
  font-display: swap;
  unicode-range: U+0020-007F, U+00A0-00FF;
}

/* Extended subset for other scripts, loaded only when needed */
@font-face {
  font-family: 'CustomFont';
  src: url('/fonts/custom-cyrillic.woff2') format('woff2');
  font-display: swap;
  unicode-range: U+0400-04FF;
}

Tools for subsetting:

Critical CSS extraction:

Extract the CSS needed for above-the-fold content and inline it in the HTML <head>. Load the remaining CSS asynchronously.

Why it matters:

How to implement:

<head>
  <style>
    /* Critical CSS inlined here */
  </style>
  <link rel="preload" href="/styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
  <noscript><link rel="stylesheet" href="/styles.css"></noscript>
</head>

Caveats:

Optimize Loading Strategy:

Container queries for component-level responsiveness:

Container queries let components adapt to their own container size rather than the viewport. This reduces the need for page-wide breakpoint overrides and makes components more reusable.

When to use:

Consult the container queries reference for syntax, practical patterns, and browser support.

Performance note:

Rendering Performance

Avoid Layout Thrashing:

// ❌ Bad: Alternating reads and writes (causes reflows)
elements.forEach(el => {
  const height = el.offsetHeight; // Read (forces layout)
  el.style.height = height * 2; // Write
});

// ✅ Good: Batch reads, then batch writes
const heights = elements.map(el => el.offsetHeight); // All reads
elements.forEach((el, i) => {
  el.style.height = heights[i] * 2; // All writes
});

Optimize Rendering:

Reduce Paint & Composite:

Animation Performance

GPU Acceleration:

/* ✅ GPU-accelerated (fast) */
.animated {
  transform: translateX(100px);
  opacity: 0.5;
}

/* ❌ CPU-bound (slow) */
.animated {
  left: 100px;
  width: 300px;
}

Smooth 60fps:

Intersection Observer:

// Efficiently detect when elements enter viewport
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      // Element is visible, lazy load or animate
    }
  });
});

React/Framework Optimization

React-specific:

Framework-agnostic:

Network Optimization

Reduce Requests:

Optimize APIs:

Optimize for Slow Connections:

Core Web Vitals Optimization

Largest Contentful Paint (LCP < 2.5s)

First Input Delay (FID < 100ms) / INP (< 200ms)

Cumulative Layout Shift (CLS < 0.1)

/* Reserve space for image */
.image-container {
  aspect-ratio: 16 / 9;
}

Performance Monitoring

Tools to use:

Key metrics:

IMPORTANT: Measure on real devices with real network conditions. Desktop Chrome with fast connection isn't representative.

NEVER:

Verify Improvements

Test that optimizations worked:

Remember: Performance is a feature. Fast experiences feel more responsive, more polished, more professional. Optimize systematically, measure ruthlessly, and prioritize user-perceived performance.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.