Performance

Performance starts with the framework defaults and the build pipeline working for you, long before any tuning at the end. The panels below are live where they can be: the page measures its own Core Web Vitals, lets you watch OnPush refuse needless work, and shows the template and image contracts that keep the initial render cheap. Everything that touches a browser-only API is guarded so it prerenders and tests the same way.

1 · Core Web Vitals, measured live

These numbers come from this very page via PerformanceObserver, updated through signals as the browser reports them. LCP fills in on load; CLS accrues as things settle; the INP proxy needs you to interact, so click around the page and watch it appear. The thresholds are Google's good / needs-improvement / poor bands.

Largest Contentful Paint Measuring…

—

Time until the biggest above-the-fold element renders, for the initial page load (LCP finalizes at first interaction). Good ≤ 2.5s.

Cumulative Layout Shift Measuring…

—

How much visible content jumps around. Good ≤ 0.1.

Interaction to Next Paint (proxy) Measuring…

—

Slowest interaction latency. Click around to feed it. Good ≤ 200ms.

2 · OnPush vs default change detection

This component runs ChangeDetectionStrategy.OnPush and its state lives in signals, so Angular only re-checks the view when a signal it reads actually changes, and it ignores the timers, events and async ticks elsewhere in the app. A default component re-checks on all of those. Press the button: the OnPush side updates exactly once per click, with no wasted passes.

OnPush + signalsthis component

0view updates

One update per real change. Unrelated app activity triggers nothing here.

Default strategyfor contrast

0+checks it would run

A default component re-checks on every event in the app, whether or not its data moved, so its real number would climb well past the clicks shown.

3 · @defer for below-the-fold cost

The block below is wrapped in @defer (on viewport). Its content (and in a real app, its component and dependencies) is split into a separate chunk that the browser only fetches once it scrolls into view. That keeps it out of the initial bundle, so the first paint ships less JavaScript and the page becomes interactive sooner.

Scroll down inside this box to trigger the deferred block ↓

4 · Incremental hydration

This block is wrapped in @defer (hydrate on viewport). The distinction from panel 3 is the whole point: plain @defer ships nothing for the block on first load and renders a placeholder on the client until the trigger fires. Incremental hydration is the inverse: the content is server-rendered and present in the prerendered HTML, so it paints immediately and is crawlable; only its JavaScript stays dormant. Angular hydrates it in place when you scroll it into view, with no flash, no re-render, and no event-handler gap thanks to event replay. You get the SEO and first-paint of SSR without paying to hydrate below-the-fold work eagerly.

Scroll down inside this box to hydrate the block ↓

Server-rendered and already in the HTML: this text was readable before any of its script loaded. Scrolling it into view hydrated it in place; nothing re-rendered.

5 · NgOptimizedImage

The image below uses Angular's NgOptimizedImage directive. Because width and height are required, the browser reserves the right box before the bytes arrive, so there's no layout shift (CLS). Marking the LCP image priority preloads it and drops lazy-loading, so it paints sooner. The directive also enforces best practices at build time (a missing dimension is a hard error).

Four palm trees in silhouette against an orange sunset over the ocean.
A fixed 240×135 box reserved up front, so nothing moves when the photo arrives. With priority the directive drops lazy-loading, sets fetchpriority="high", and, when the page is rendered on the server, adds a preload link for the image to the document head. Mark the one image that is your page's largest paint this way; section 7 shows the formats behind it.

6 · Bundle budgets & lazy routes

The cheapest JavaScript is the kind that never ships. This app guards that on two fronts, so a regression is caught in CI rather than in the field.

How this project keeps the bundle honest
Every route in this dashboard is lazy-loaded with loadComponent, so a page's code only downloads when you navigate to it, including this one. On top of that, the build defines bundle budgets: the production build fails if the initial bundle grows past its ceiling. Together they mean adding a heavy page can't silently inflate what every visitor pays on first load.

7 · Modern image formats (AVIF, WebP)

The same photo, as JPEG, WebP and AVIF, with the bytes each one actually cost. Then the two ways to serve the small one without breaking the browsers that can't decode it: <picture>, where the browser picks the first format it supports, and NgOptimizedImage with a loader, which generates the srcset but can't sit inside <picture>, so it serves one format to everyone. The image in section 5 shows the other half of the contract: priority for the image that is the page's largest paint.

JPEG—
WebP—
AVIF—

All three are 640×360. JPEG at mozjpeg quality 80, WebP at 75, AVIF at 50: each encoder's setting for "looks like the photo", not one number applied to all three. The sizes are read from this page's Resource Timing entries once each image loads.

Let the browser choose: <picture>

Four palm trees in silhouette against an orange sunset over the ocean.

This browser loaded …

NgOptimizedImage with a loader

The same palm trees, served through NgOptimizedImage and a custom loader.

The loader handed this browser …

Photo by Jesse Collins on Unsplash

Loading the source panels…

8 · Lighthouse as a build gate

Every ready pull request that touches the dashboard, and the weekly run on main, runs Lighthouse against the dashboard's prerendered build, and a miss fails the check. scripts/lighthouse-gate.mjs serves the build the way the host does (text gzipped) and runs Lighthouse with analytics blocked, since that loads after the page and its timing belongs to Google's servers. scripts/lighthouse-budget.mjs holds the numbers it is judged against.

  • Four pages:/, /performance/, /platform/ and /defer/. The front door, the two pages built around images and the heaviest markup, and the page whose point is a cheap first load.
  • Mobile and desktop: each page is measured on Lighthouse's simulated phone and again with its desktop config.
  • Median of three: three runs per page and form factor; the run with the median performance score is the one judged.
  • Accessibility, Best Practices and SEO must be 100. Those scores don't drift between runs, so anything less fails at once and names the failing audits.
  • Performance fails on a real drop, not on noise: below 85 on mobile or 95 on desktop it fails; anything short of 100 is only a warning. A page that misses on timing alone (the score, Largest Contentful Paint or Total Blocking Time) gets three more runs and is judged on the median of all six before it fails.
  • Budgets catch what moves the score: Largest Contentful Paint (2,800 ms mobile, 1,000 ms desktop), Total Blocking Time (500 ms, 150 ms) and Cumulative Layout Shift (0.1); bytes over the wire for the site's own files (300 KB of script, 120 KB of images on mobile and 160 KB on desktop, 40 KB of HTML, 10 KB of CSS); and any JPEG or PNG over 20 KB, which means a modern-format source is missing. Layout shift, bytes and image formats fail at once, because they don't change between runs.
View source: the budget the gate enforceslighthouse-budget.mjs
ts
/*
 * What scripts/lighthouse-gate.mjs holds the dashboard's prerendered build to. Each page is
 * measured on a simulated phone and on desktop, several times, and the median run is judged.
 *
 * Accessibility, Best Practices and SEO don't drift between runs, so they must stay at 100.
 * The performance score does drift, by several points on a shared CI machine, so it fails only
 * on a real drop and warns on anything short of 100. The budgets catch the regressions that
 * actually move it: a slower largest paint, layout shift, main-thread blocking, more bytes, and
 * an image shipped without a modern format.
 */
export const RUNS = 3;

// The front door, the two pages built around images and the platform's heaviest markup, and the
// @defer page whose whole point is a cheap first load.
export const PAGES = ['/', '/performance/', '/platform/', '/defer/'];

export const FORM_FACTORS = {
  mobile: {
    // GitHub's runner, 2026-10-23: score 92–98, LCP 2.01–2.28 s, TBT 80–266 ms, CLS 0. The portfolio
    // saw the same commit measure TBT 285 ms on one runner and 438 ms on another, so mobile timing
    // floors sit well below the spread (and the gate re-measures before failing on timing); the
    // byte, format and CLS budgets do the precise work.
    performance: { fail: 0.85 },
    metrics: {
      'largest-contentful-paint': 2800,
      'cumulative-layout-shift': 0.1,
      'total-blocking-time': 500,
    },
  },
  desktop: {
    performance: { fail: 0.95 },
    // Same run: perf 100, LCP 0.44–0.48 s, TBT 0 ms.
    metrics: {
      'largest-contentful-paint': 1000,
      'cumulative-layout-shift': 0.1,
      'total-blocking-time': 150,
    },
  },
};

// Bytes over the wire, this site's own files only, per page load. On 2026-10-23 the heaviest page
// took JS 275 (/platform), images 17, HTML 29, CSS 4. Raise one on purpose, in the PR that needs it.
export const TRANSFER_BUDGET_KB = {
  script: 300,
  image: { mobile: 120, desktop: 160 },
  document: 40,
  stylesheet: 10,
};

// An image Chrome downloads as JPEG or PNG means a modern-format source is missing. Tiny files
// (icons, the brandmark) are exempt.
export const LEGACY_IMAGE_MAX_KB = 20;
View source: the gate scriptlighthouse-gate.mjs

measure() runs a page three times, median() picks the run with the middle performance score, and check() turns that run into failures and warnings. The re-measure on a timing-only miss is in the main loop near the top.

ts
/*
 * Lighthouse as a build gate for demo.miguelcarino.com. Serves the dashboard's prerendered build
 * the way the host does (gzip for text), runs Lighthouse on the pages in
 * scripts/lighthouse-budget.mjs, mobile and desktop, and fails if the median run misses the budget.
 *
 *   npx nx build dashboard && npm run check:lighthouse
 *
 * Reports (HTML + JSON, one per median run) go to lighthouse-reports/ for CI to upload.
 * Analytics is blocked: it loads after the page anyway, and its timing belongs to Google's
 * servers, not to this build.
 */
import {
  appendFileSync,
  createReadStream,
  existsSync,
  mkdirSync,
  statSync,
  writeFileSync,
} from 'node:fs';
import { createServer } from 'node:http';
import { extname, join, resolve } from 'node:path';
import { createGzip } from 'node:zlib';
import { chromium } from '@playwright/test';
import * as chromeLauncher from 'chrome-launcher';
import lighthouse from 'lighthouse';
import desktopConfig from 'lighthouse/core/config/desktop-config.js';
import {
  FORM_FACTORS,
  LEGACY_IMAGE_MAX_KB,
  PAGES,
  RUNS,
  TRANSFER_BUDGET_KB,
} from './lighthouse-budget.mjs';

const ROOT = resolve('dist/apps/dashboard/browser');
const OUT = resolve('lighthouse-reports');

if (!existsSync(join(ROOT, 'index.html'))) {
  console.error('No build at dist/apps/dashboard/browser. Run `npx nx build dashboard` first.');
  process.exit(1);
}

const server = await serve(ROOT);
const origin = `http://localhost:${server.address().port}`;
const chrome = await chromeLauncher.launch({
  // CHROME_PATH for a machine whose Chrome isn't where Playwright installs it.
  chromePath: process.env['CHROME_PATH'] ?? chromium.executablePath(),
  chromeFlags: ['--headless=new', '--no-sandbox'],
});
mkdirSync(OUT, { recursive: true });

const failures = [];
const warnings = [];
const rows = [];

try {
  for (const page of PAGES) {
    for (const [formFactor, budget] of Object.entries(FORM_FACTORS)) {
      let runs = await measure(`${origin}${page}`, formFactor);
      let verdict = check(page, formFactor, budget, median(runs), runs);
      /*
       * Timing (the score, LCP, TBT) swings with how busy the CI machine is: the same commit has
       * measured TBT 285 ms in one run and 438 ms in another. A page that misses only on timing
       * gets a second set of runs, judged on the median of all of them, before it fails. Bytes,
       * image formats and the three 100s don't move between runs, so those fail at once.
       */
      if (verdict.timing.length && !verdict.fixed.length) {
        runs = runs.concat(await measure(`${origin}${page}`, formFactor));
        verdict = check(page, formFactor, budget, median(runs), runs);
      }
      rows.push(verdict.row);
      console.log(verdict.row);
      failures.push(...verdict.fixed, ...verdict.timing);
      warnings.push(...verdict.warnings);
      const name = `${formFactor}${page.replaceAll('/', '_')}`.replace(/_$/, '');
      writeFileSync(join(OUT, `${name}.json`), JSON.stringify(median(runs)));
    }
  }
} finally {
  await chrome.kill();
  server.close();
}

// On GitHub Actions, annotations put each result on the PR's checks page and the table in the
// run summary, so nobody has to open the log.
const ci = process.env['GITHUB_ACTIONS'] === 'true';
for (const w of warnings) console.log(ci ? `::warning title=Lighthouse::${w}` : `warn  ${w}`);
for (const f of failures) console.log(ci ? `::error title=Lighthouse::${f}` : `FAIL  ${f}`);
if (ci && process.env['GITHUB_STEP_SUMMARY']) {
  appendFileSync(
    process.env['GITHUB_STEP_SUMMARY'],
    `### Lighthouse (median of ${RUNS})\n\n\`\`\`\n${rows.join('\n')}\n\`\`\`\n`,
  );
}
if (ci) console.log(`::notice title=Lighthouse results::${rows.join(' %0A')}`);
if (failures.length) {
  console.log(`\nLighthouse gate: ${failures.length} failure(s). Reports in lighthouse-reports/.`);
  process.exit(1);
}
console.log('\nLighthouse gate passed.');

async function measure(url, formFactor) {
  const runs = [];
  for (let i = 0; i < RUNS; i++) runs.push(await audit(url, formFactor));
  return runs;
}

function median(runs) {
  return [...runs].sort((a, b) => score(a) - score(b))[Math.floor(runs.length / 2)];
}

async function audit(url, formFactor) {
  const flags = {
    port: chrome.port,
    output: 'json',
    logLevel: 'error',
    onlyCategories: ['performance', 'accessibility', 'best-practices', 'seo'],
    blockedUrlPatterns: ['*googletagmanager.com*', '*google-analytics.com*'],
  };
  const result = await lighthouse(url, flags, formFactor === 'desktop' ? desktopConfig : undefined);
  return result.lhr;
}

function score(lhr) {
  return lhr.categories.performance.score;
}

function check(page, formFactor, budget, lhr, runs) {
  const fixed = [];
  const timing = [];
  const warns = [];
  const where = `${formFactor.padEnd(7)} ${page}`;
  const scores = runs.map((r) => Math.round(score(r) * 100)).join('/');
  const cats = Object.fromEntries(Object.entries(lhr.categories).map(([k, c]) => [k, c.score]));
  const metric = (id) => lhr.audits[id].numericValue;
  // Bytes by type, this site's own requests only.
  const own = lhr.audits['network-requests'].details.items.filter((r) =>
    r.url.startsWith(new URL(lhr.finalDisplayedUrl).origin),
  );
  const kb = (type) =>
    own.filter((r) => r.resourceType === type).reduce((n, r) => n + (r.transferSize ?? 0), 0) /
    1024;

  const row =
    `${where.padEnd(44)} perf ${String(Math.round(cats.performance * 100)).padStart(3)} (runs ${scores})` +
    `  a11y ${cats.accessibility * 100}  bp ${cats['best-practices'] * 100}  seo ${cats.seo * 100}` +
    `  LCP ${Math.round(metric('largest-contentful-paint'))}ms  TBT ${Math.round(metric('total-blocking-time'))}ms` +
    `  CLS ${metric('cumulative-layout-shift').toFixed(3)}` +
    `  KB js ${kb('Script').toFixed(0)} img ${kb('Image').toFixed(0)} doc ${kb('Document').toFixed(0)} css ${kb('Stylesheet').toFixed(0)}`;

  for (const key of ['accessibility', 'best-practices', 'seo']) {
    if (cats[key] < 1)
      fixed.push(
        `${where}: ${key} ${Math.round(cats[key] * 100)}, must be 100 (${failingAudits(lhr, key)})`,
      );
  }
  if (cats.performance < budget.performance.fail) {
    timing.push(
      `${where}: performance ${Math.round(cats.performance * 100)}, floor ${budget.performance.fail * 100}`,
    );
  } else if (cats.performance < 1) {
    warns.push(`${where}: performance ${Math.round(cats.performance * 100)}`);
  }
  for (const [id, max] of Object.entries(budget.metrics)) {
    if (metric(id) > max)
      (id === 'cumulative-layout-shift' ? fixed : timing).push(
        `${where}: ${id} ${round(metric(id))} over ${max}`,
      );
  }

  for (const [label, type] of [
    ['script', 'Script'],
    ['image', 'Image'],
    ['document', 'Document'],
    ['stylesheet', 'Stylesheet'],
  ]) {
    const limit =
      typeof TRANSFER_BUDGET_KB[label] === 'object'
        ? TRANSFER_BUDGET_KB[label][formFactor]
        : TRANSFER_BUDGET_KB[label];
    if (kb(type) > limit)
      fixed.push(`${where}: ${label} ${kb(type).toFixed(0)} KB over ${limit} KB`);
  }
  for (const r of own) {
    const legacy = /image\/(jpeg|png)/.test(r.mimeType ?? '');
    if (r.resourceType === 'Image' && legacy && r.transferSize / 1024 > LEGACY_IMAGE_MAX_KB) {
      fixed.push(
        `${where}: ${r.url.replace(/^https?:\/\/[^/]+/, '')} is ${r.mimeType} (${(r.transferSize / 1024).toFixed(0)} KB); add a modern-format source`,
      );
    }
  }
  return { row, fixed, timing, warnings: warns };
}

function failingAudits(lhr, category) {
  return lhr.categories[category].auditRefs
    .filter(
      (ref) => ref.weight > 0 && lhr.audits[ref.id].score !== null && lhr.audits[ref.id].score < 1,
    )
    .map((ref) => ref.id)
    .join(', ');
}

function round(n) {
  return n < 1 ? n.toFixed(3) : Math.round(n);
}

// The host gzips text and serves each prerendered route from its folder's index.html.
function serve(root) {
  const types = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.webmanifest': 'application/manifest+json',
    '.svg': 'image/svg+xml',
    '.ico': 'image/x-icon',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.avif': 'image/avif',
    '.webp': 'image/webp',
    '.md': 'text/markdown',
    '.txt': 'text/plain',
    '.xml': 'application/xml',
  };
  const server = createServer((req, res) => {
    let file = join(root, decodeURIComponent(new URL(req.url, 'http://x').pathname));
    if (existsSync(file) && statSync(file).isDirectory()) file = join(file, 'index.html');
    if (!file.startsWith(root) || !existsSync(file)) file = join(root, 'index.html');
    const type = types[extname(file)] ?? 'application/octet-stream';
    res.setHeader('content-type', type);
    if (/^(text|application)\//.test(type) && /gzip/.test(req.headers['accept-encoding'] ?? '')) {
      res.setHeader('content-encoding', 'gzip');
      createReadStream(file).pipe(createGzip()).pipe(res);
    } else {
      createReadStream(file).pipe(res);
    }
  });
  return new Promise((done) => server.listen(0, () => done(server)));
}