Claude
Skills
Sign in
Back

frontend-fullchain-optimization

Included with Lifetime
$97 forever

Frontend full-chain performance optimization guide based on Web Vitals metrics. Provides metric thresholds, diagnostic methods, and optimization strategies for LCP, FCP, INP, CLS, TTFB, TBT. Use when optimizing frontend performance, analyzing Web Vitals, reducing page load time, fixing layout shifts, improving interaction responsiveness, or reviewing frontend code for performance issues.

Web Dev

What this skill does


# Frontend Full-Chain Performance Optimization Guide

A frontend performance diagnostic and optimization system based on Web Vitals core metrics. Core principle: **User-centric — optimization is about doing less, not more.**

## Metric Threshold Quick Reference

| Metric | Good | Needs Improvement | Poor | Unit | Focus |
| ------ | ------ | ------------------- | ------ | ------ | -------- |
| LCP | ≤ 2.5s | 2.5s - 4s | > 4s | Time | Largest Contentful Paint |
| FCP | ≤ 1.8s | 1.8s - 3s | > 3s | Time | First Contentful Paint |
| INP | ≤ 200ms | 200ms - 500ms | > 500ms | Time | Interaction to Next Paint |
| CLS | ≤ 0.1 | 0.1 - 0.25 | > 0.25 | Score | Visual Stability |
| TTFB | ≤ 800ms | 800ms - 1.8s | > 1.8s | Time | Time to First Byte |
| FID | ≤ 100ms | 100ms - 300ms | > 300ms | Time | First Input Delay |
| TBT | Tasks > 50ms are long tasks | — | — | Time | Total Blocking Time |

**Measurement advice**: Don't rely on a single P75. Combine P60/P75/P90/P99 percentiles with daily avg/max/min trend lines. Desktop: target P98+; Mobile core pages: target P95–P99.

## Diagnostic Decision Tree

```text
Page loads slowly?
├── TTFB > 800ms → Network/server issue → See "TTFB Optimization"
├── FCP > 1.8s → Resource blocking/large files → See "FCP Optimization"
├── LCP > 2.5s
│   ├── TTFB & FCP normal → Slow viewport resource loading → See "LCP Optimization"
│   └── TTFB or FCP abnormal → Fix upstream metrics first
├── INP > 200ms → Long tasks blocking main thread → See "INP Optimization"
├── CLS > 0.1 → Layout shifts → See "CLS Optimization"
└── Lighthouse Performance Score
    ├── > 80: Few issues
    ├── 60-80: Needs focused analysis, priority: FCP → LCP → CLS
    └── < 60: Severe issues, full audit required
```

## INP Optimization (Interaction Responsiveness)

**Diagnosis**: Chrome Performance panel — look for long tasks (> 50ms, highlighted red); inspect event handler duration in the flame chart.

**Strategy — Break long tasks into shorter ones**:

| Method | Mechanism | Use Case |
| ------ | ------ | ---------- |
| `setTimeout(fn, 0)` | Creates a new macrotask at the end of the queue | Non-urgent network requests, DB operations |
| `Promise.resolve().then(fn)` | Creates a microtask, runs immediately after current macrotask | Secondary tasks needing faster execution |
| `requestAnimationFrame(fn)` | Runs before next repaint | Rendering-related tasks |
| `requestIdleCallback(fn)` | Lowest priority, runs when main thread is idle | Analytics, logging |
| `scheduler.postTask(fn, {priority})` | Fine-grained priority control | Scenarios requiring precise scheduling |

**postTask priorities**: `user-blocking` (high) > `user-visible` (medium) > `background` (low)

**Layout & Rendering Optimization**:
- Reduce `calc()` usage frequency; avoid unnecessary pseudo-class selectors (`nth-child`, `nth-last-child`, `not()`)
- Avoid frequent JS modifications to element position/size; use className or cssText for batch updates
- Avoid alternating DOM read/write in loops (layout thrashing): cache reads into variables first, then batch write
- Use skeleton screens for lazy-loaded content
- Use `<></>` (Fragment) instead of meaningless `<div>` wrappers
- DOM nodes > 800: caution; > 1400: excessive
- Use virtualization for long lists (react-window / vue-virtual-scroll-list)
- Swiper lists: preload only current item ± 1

**CSS Optimization**:
- Avoid `table` layout; reduce deeply nested CSS selectors
- Use GPU-accelerated animations: `transform`/`opacity` trigger compositing layer; avoid `top`/`left` which trigger reflow
- Use semantic HTML elements; avoid meaningless tags (e.g., use `<button>` not `<div>` for buttons)

## TTFB Optimization (Network & Server)

**Diagnostic formula**: `TTFB ≈ HTTP request time + Server processing time + HTTP response time`

**Diagnosis**: DevTools Network panel → click request → Timing → "Waiting for server response" = TTFB.

**TTFB differences by page type**: Static pages (CDN direct, fastest) < SPA (tiny HTML shell, near-static) < SSR (Node.js computation required, slowest). Adjust baseline by page type.

| Direction | Strategy |
| ------ | ------ |
| General | CDN acceleration (solves 90%+; proactively purge CDN cache after deploys), HTTP/2 multiplexing, Gzip compression, code splitting & dynamic imports |
| UX | Web Workers for heavy requests, DNS prefetch `<link rel="dns-prefetch">`, preconnect `<link rel="preconnect">` |
| Server (SSR) | Internal network for APIs, Redis cache for low-frequency data, reduce redirects, pre-generate static pages at build time |
| Resource Caching | App hot-update: pre-download HTML/JS/CSS locally (TTFB ≈ 0), PWA Service Worker offline cache |

## FCP Optimization (White Screen & First Content)

**Diagnostic formula**: `FCP ≈ TTFB + Resource download time + DOM parse time + Render time`

**White screen time ≈ FCP time**. Target: instant open (< 1s).

| Strategy | Details |
| ------ | ------ |
| Remove render-blocking resources | Add `defer` or `async` to script tags; non-critical JS → NPM bundle or framework components (e.g., `next/script`) |
| Reduce JS/CSS size | Remove unused code, Tree Shaking, code splitting |
| Control network payload | Compress above-fold images, use WebP/AVIF, lazy-load videos with placeholders |
| Caching strategy | `Cache-Control: max-age=31536000` (static assets cached 1 year); JS/CSS as needed |
| Shorten critical request depth | Reduce nested resource dependencies (e.g., CSS @import chains); flatten critical resource request chains |
| Font optimization | See "Font Optimization Strategies" below |
| White screen solutions | PWA (international markets); App hot-update local loading (domestic markets) |

## Font Optimization Strategies

| Approach | Description |
| ------ | ------ |
| Limit font count | Use only one custom font + system font fallback; don't use different Web Fonts for body and p |
| Prefer WOFF2 | 30% better compression than WOFF, supported by all modern browsers |
| `unicode-range` subsetting | Define character ranges (e.g., CJK U+4E00-9FA5); browser downloads only needed subsets |
| `local()` local fonts | For apps with bundled fonts: `src: local('Font Name'), url(...)` reads local font first, no network request |
| `font-display` strategy | `swap`: system font first then replace (lowest CLS); `optional`: with preload (no re-layout on failure); `block`: wait (blocks rendering); `fallback`/`auto`: compromise |
| CSS Font Loading API | `new FontFace()` + `font.load()` + `document.fonts.ready.then()` — programmatic control of font download timing and swap logic |
| Slow network fallback | Use `navigator.connection` to detect; slow users get system default fonts |

## LCP Optimization (Largest Contentful Paint)

**Diagnosis**: Performance panel — find the LCP marker element; Lighthouse report "Largest Contentful Paint element" entry.

**4 element types LCP can mark**:
1. `<img>` elements (most common) and `<image>` within SVG
2. `<video>` `poster` attribute image or first frame
3. Elements with CSS `url()` background images
4. Block-level elements containing text nodes

**Key insights**:
- LCP time is always ≥ FCP time
- If TTFB and FCP are normal but LCP is abnormal → problem is viewport resource loading
- SPA: FCP matters more than LCP; SSR/MPA: LCP matters more than FCP

| Strategy | Details |
| ------ | ------ |
| Preload LCP image | `<link rel="preload" href="..." as="image">` |
| Framework image components | Use `next/image` (includes priority & format optimization); set `priority={true}` |
| Split large images | Slice large background images into smaller pieces |
| Image format | PNG/JPEG → WebP/AVIF, saves 30%+ size |
| Cloud image params | Dynamically set image size/quality/format per device (e.g., Alibaba Cloud OSS params) |
| Rich text images | Extract image URLs from content, set `<link rel="preload">` in advance |
| Avoid duplicate preloads | When using framework image components (e.g., `next/image`) with `priority`, don't also add manual `<link rel="pre

Related in Web Dev