Lab 13: Performance Optimization

Time: 30 minutes | Level: Practitioner | Docker: docker run -it --rm node:20-alpine sh

Overview

Optimize HTML/CSS performance: extract critical CSS, use resource hints, understand Core Web Vitals (LCP/CLS/INP), leverage content-visibility, and implement lazy loading.


Step 1: Critical CSS (Above-the-Fold Inline)

Critical CSS = the minimum styles needed to render above-the-fold content:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Page</title>

  <!-- 1. Inline critical CSS (no network request) -->
  <style>
    /* Only what's needed for above-the-fold content */
    *, *::before, *::after { box-sizing: border-box; }
    body { margin: 0; font-family: system-ui, sans-serif; }
    .hero { min-height: 100svh; display: flex; align-items: center; justify-content: center; }
    .nav { position: sticky; top: 0; z-index: 100; background: white; }
    h1 { font-size: clamp(2rem, 5vw, 4rem); }
  </style>

  <!-- 2. Non-critical CSS: async load -->
  <link rel="preload" href="/css/main.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
  <noscript><link rel="stylesheet" href="/css/main.css"></noscript>

  <!-- 3. Resource hints (see Step 2) -->
</head>

Step 2: Resource Hints

Priority:

  • preconnectpreload → page load → prefetch → idle


Step 3: async vs defer Scripts


Step 4: Core Web Vitals

LCP — Largest Contentful Paint (target: ≤2.5s)

CLS — Cumulative Layout Shift (target: ≤0.1)

INP — Interaction to Next Paint (target: ≤200ms)


Step 5: content-visibility

💡 Google reported up to 7× rendering speedup using content-visibility: auto on a news page with thousands of off-screen articles.


Step 6: loading=lazy and Image Optimization


Step 7: CSS Performance Patterns


Step 8: Capstone — CSS Minifier

📸 Verified Output:


Summary

Technique
Implementation
Metric Impact

Critical CSS inline

<style> in <head>

FCP, LCP

preload

<link rel="preload">

LCP

preconnect

<link rel="preconnect">

TTFB

defer

<script defer>

TTI

content-visibility

content-visibility: auto

INP, rendering

contain-intrinsic-size

auto 500px

CLS

fetchpriority="high"

On LCP image

LCP

loading="lazy"

On below-fold images

LCP, bandwidth

width/height on images

<img width="800">

CLS

Transform animations

transform not top/left

INP, FPS

Last updated