EthicsComputerCourses
Join training +91 90532 10052

Production HTML Optimization

HTML · Lesson 216 of 234 Advanced 12 min read Updated

By the end of this lesson you will be able to run a final optimisation pass on a finished page, decide what is safe to remove from HTML, inline critical CSS, subset an Indian-language font, put third-party scripts on a budget and prove the result with before and after measurements.

What you should know first: Production Deployment & Optimization, HTML Performance Optimization, Core Web Vitals Fundamentals, Lighthouse & HTML Auditing and CDN & Static Asset Delivery. Lighthouse Performance Auditing covers reading reports in depth.

Measure first, then change one thing at a time

An optimisation pass is like a tailor's final fitting before a wedding: measure, adjust, measure again. There are two kinds of data:

  • Lab data comes from a test you run, such as Lighthouse, on one device with fixed throttling. It is repeatable, so it suits before/after comparisons.
  • Field data comes from real visitors. The Chrome UX Report (CrUX) collects it from Chrome users over 28 days and shows it in PageSpeed Insights and Search Console. Small sites often have too little traffic to appear, so measure your own visitors too.

The web-vitals library (version 6.2.3 on npm in November 2026) reports Core Web Vitals from real visits. This sends each value to your own endpoint:

JavaScript
import { onLCP, onINP, onCLS } from "web-vitals";

function send(metric) {
  navigator.sendBeacon("/vitals", JSON.stringify({ name: metric.name, value: metric.value, page: location.pathname }));
}
onLCP(send);
onINP(send);
onCLS(send);

Step 1: a real before and after in the lab

Here is a one-page site for Jaipur heritage walks, in two versions served from a local Node server with gzip:

BeforeAfter
A full CSS framework (227 KB) plus site.css, both render-blockingThe few rules the page uses, inlined in <style>
A 600 ms "chat widget" script in <head>The widget loads only when someone clicks "Chat with us"
A 2400x1500 JPEG (1.3 MB) with loading="lazy" and no sizeAn 800x500 WebP (84 KB) with width, height and fetchpriority="high"
A promo banner inserted above the image after 1.5 sSpace for the banner reserved from the start

Lighthouse 13.6.0 ran on each version with its default mobile settings (simulated slow 4G and 4x CPU slowdown):

Terminal
npx lighthouse http://127.0.0.1:8099/before.html --only-categories=performance --output=json --output-path=before.json --chrome-flags="--headless=new" --quiet
npx lighthouse http://127.0.0.1:8099/after.html --only-categories=performance --output=json --output-path=after.json --chrome-flags="--headless=new" --quiet
node report.mjs
JavaScript
// report.mjs: print the key numbers from two Lighthouse JSON reports
import { readFileSync } from "node:fs";

const rows = [
  ["Performance score", (r) => Math.round(r.categories.performance.score * 100)],
  ["First Contentful Paint", (r) => r.audits["first-contentful-paint"].displayValue],
  ["Largest Contentful Paint", (r) => r.audits["largest-contentful-paint"].displayValue],
  ["Total Blocking Time", (r) => r.audits["total-blocking-time"].displayValue],
  ["Cumulative Layout Shift", (r) => r.audits["cumulative-layout-shift"].displayValue],
  ["Main-thread work", (r) => r.audits["mainthread-work-breakdown"].displayValue],
  ["Page weight", (r) => Math.round(r.audits["total-byte-weight"].numericValue / 1024) + " KiB"],
];

const before = JSON.parse(readFileSync("before.json", "utf8"));
const after = JSON.parse(readFileSync("after.json", "utf8"));
console.log("Metric".padEnd(26) + "Before".padEnd(14) + "After");
for (const [name, get] of rows) {
  console.log(name.padEnd(26) + String(get(before)).padEnd(14) + get(after));
}
Output
Metric                    Before        After
Performance score         68            100
First Contentful Paint    3.4 s         0.7 s
Largest Contentful Paint  8.0 s         1.4 s
Total Blocking Time       0 ms          70 ms
Cumulative Layout Shift   0.035         0
Main-thread work          3.0 s         0.6 s
Page weight               1349 KiB      85 KiB

This is one run on one Windows laptop, so treat the numbers as an example, not a benchmark. Run each version three to five times and compare medians before you trust a difference.

Total Blocking Time was 0 ms "before" because the widget ran before the first paint, so its cost shows up in First Contentful Paint. The 70 ms "after" is run-to-run noise. Lighthouse named the causes in the "before" report: "Render-blocking requests", "Improve image delivery: Est savings of 1,271 KiB", "Reduce unused CSS: Est savings of 29 KiB" and "LCP request discovery" (the lazy hero image).

Step 2: compare two versions in your browser

You can see the biggest effect, a blocking script, without any tools. This page loads the same content twice in frames, once with 400 ms of widget work in the head and once with that work after the page has painted:

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Before and after: first paint</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    .frames { display: flex; gap: 12px; flex-wrap: wrap; }
    iframe { width: 260px; height: 140px; border: 1px solid #888; }
    table { border-collapse: collapse; margin-top: 12px; }
    td, th { border: 1px solid #aaa; padding: 4px 10px; text-align: left; }
  </style>
</head>
<body>
  <h1>Same page, two loading strategies</h1>
  <p>Both versions run 400 ms of "chat widget" work. Before: in the head. After: once the page has painted.</p>
  <button type="button" id="run">Run the comparison</button>
  <div class="frames">
    <iframe id="before" title="Before version"></iframe>
    <iframe id="after" title="After version"></iframe>
  </div>
  <table>
    <thead><tr><th>Version</th><th>First Contentful Paint</th><th>Load event</th></tr></thead>
    <tbody id="results"></tbody>
  </table>
  <script>
    const widget = "const end = performance.now() + 400; while (performance.now() < end) {}";
    const content = "<h2>Jaipur Heritage Walks</h2><p>Walks every morning at 7.</p>";
    const pages = {
      before: `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Before</title>
        <script>${widget}<\/script></head><body>${content}</body></html>`,
      after: `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>After</title></head>
        <body>${content}<script>
          addEventListener("load", () => setTimeout(() => { ${widget} }, 500));
        <\/script></body></html>`
    };

    function measure(name) {
      return new Promise((resolve) => {
        const frame = document.getElementById(name);
        frame.addEventListener("load", () => {
          setTimeout(() => {
            const perf = frame.contentWindow.performance;
            const fcp = perf.getEntriesByName("first-contentful-paint")[0];
            const nav = perf.getEntriesByType("navigation")[0];
            resolve([name, fcp ? fcp.startTime.toFixed(0) + " ms" : "not reported",
                     nav ? nav.loadEventStart.toFixed(0) + " ms" : "not reported"]);
          }, 300);
        }, { once: true });
        frame.srcdoc = pages[name];
      });
    }

    document.getElementById("run").addEventListener("click", async () => {
      const body = document.getElementById("results");
      body.replaceChildren();
      for (const name of ["before", "after"]) {   // one at a time, so they do not compete
        const row = document.createElement("tr");
        for (const cell of await measure(name)) {
          const td = document.createElement("td");
          td.textContent = cell;
          row.append(td);
        }
        body.append(row);
      }
    });
  </script>
</body>
</html>

In one headless Chrome run the table showed 472 ms for "before" and 56 ms for "after". Your numbers will differ, but "before" is always at least 400 ms later: the browser cannot paint while a head script runs.

Minifying HTML safely

A minifier removes whitespace and comments, but whitespace is sometimes content. Our test page has inline nav links, bold and italic words, a <pre>, a <textarea> and an Apache server-side include comment. Here are two settings of html-minifier-terser 7.2.0:

JavaScript
import { readFileSync } from "node:fs";
import { minify } from "html-minifier-terser";

const html = readFileSync("page.html", "utf8");

const safe = await minify(html, {
  collapseWhitespace: true,
  conservativeCollapse: true,   // keep one space where there was whitespace
  removeComments: true,
});

const risky = await minify(html, {
  collapseWhitespace: true,
  collapseInlineTagWhitespace: true,
  removeComments: true,
  removeOptionalTags: true,
  removeAttributeQuotes: true,
});

console.log(`original: ${html.length} bytes`);
console.log(`safe:     ${safe.length} bytes`);
console.log(`risky:    ${risky.length} bytes\n`);
console.log("SAFE\n" + safe + "\n");
console.log("RISKY\n" + risky);
Output
original: 561 bytes
safe:     508 bytes
risky:    429 bytes

SAFE
<!DOCTYPE html> <html lang="en-IN"> <head> <meta charset="utf-8"> <title>Jaipur Block Prints</title> <link rel="stylesheet" href="/css/site.css"> </head> <body> <nav> <a class="pill" href="/">Home</a> <a class="pill" href="/sarees">Sarees</a> <a class="pill" href="/contact">Contact</a> </nav> <p>Hand printed in <b>Sanganer</b> <i>since 1985</i>.</p> <pre>
order:
  item: dupatta
  qty:  2
</pre> <textarea name="note">
Gift wrap, please.
</textarea> <!--#include virtual="/footer.html" --> </body> </html> 

RISKY
<!DOCTYPE html><html lang=en-IN><meta charset=utf-8><title>Jaipur Block Prints</title><link rel=stylesheet href=/css/site.css><nav><a class=pill href=/ >Home</a><a class=pill href=/sarees>Sarees</a><a class=pill href=/contact>Contact</a></nav><p>Hand printed in<b>Sanganer</b><i>since 1985</i>.<pre>
order:
  item: dupatta
  qty:  2
</pre><textarea name=note>
Gift wrap, please.
</textarea><!--#include virtual="/footer.html" -->

What to notice:

  • The risky version renders "Hand printed inSanganersince 1985" and glues the nav links together. Spaces between inline elements are real text.
  • Both kept <pre> and <textarea> content, and the <!--#include comment, which this minifier preserves by default. Check your own tool: some comments are instructions for a server or a tool.
  • Dropping </p>, <head> and quotes is valid HTML, but it makes the output hard to debug and saves little.

Is it worth it? On a real 106 KB lesson page, the safe settings cut the raw size to 99.3 KB but the gzip size only from 18.2 KB to 17.7 KB. Compression already removes most repeated whitespace. Minify safely, then spend your effort elsewhere.

Inlining critical CSS

Critical CSS is the CSS needed for the first screen. Inlining it in <style> lets the browser paint without waiting for a stylesheet download. Beasties, the maintained fork of the older Critters tool, does this at build time:

JavaScript
import { readFileSync } from "node:fs";
import Beasties from "beasties";

const beasties = new Beasties({ path: "crit" });   // folder where /css/site.css lives
const html = readFileSync("crit/index.html", "utf8");
console.log(await beasties.process(html));
Output
Inlined 127 bytes (49% of original 256 bytes) of css/site.css.
Time 333ms
<!DOCTYPE html>
<html lang="en-IN" data-beasties-container>
<head>
  <meta charset="utf-8">
  <title>Pune Book Fair</title>
  <style>body{margin:0;font-family:system-ui, sans-serif}.hero{background:#1d3557;color:white;padding:48px 16px}.lead{font-size:1.25rem}</style><link rel="preload" href="/css/site.css" as="style">
</head>
<body>
  <header class="hero"><h1>Pune Book Fair 2026</h1></header>
  <main><p class="lead">Over 200 stalls at the College of Engineering ground.</p></main>
<link rel="stylesheet" href="/css/site.css"></body>
</html>

(The first two lines are the tool's log, shown in colour in a terminal.) It kept only rules whose selectors match elements in this HTML and moved the full stylesheet to the end of <body>. Beasties does not render the page, so it cannot tell what is above the fold. Keep the inline CSS small, roughly a few KB, because it is downloaded again with every page and is not cached separately.

Removing unused CSS and JavaScript

Open DevTools, press Ctrl+Shift+P, run "Show Coverage" and reload. Each file shows how many bytes were used on this page. A large unused share in a framework file means you should include only the components you need. Tools such as PurgeCSS remove unused selectors automatically, but they only see class names written out in your files. A class built in JavaScript, such as "badge-" + status, is removed by mistake unless you add it to the tool's safelist. Test every page type after purging.

Preload and preconnect review

Re-read every hint from Resource Hints in the final HTML. Remove preconnect to origins the page no longer uses, keep at most one or two preload hints (usually the LCP image or the main font), and check that no preload is reported as "unused" in the Console.

Fonts for Indian languages

A Devanagari, Tamil or Bengali font is often much larger than a Latin one, because conjuncts and vowel signs need many glyphs. First, subset it to the scripts you use. With fontTools, keep all OpenType layout features, or conjuncts such as क्ष and vowel signs break apart:

Terminal
pip install fonttools brotli
pyftsubset NotoSansDevanagari-Regular.ttf --unicodes="U+0900-097F,U+200C-200D,U+20B9,U+25CC" --layout-features="*" --flavor=woff2 --output-file=devanagari-sub.woff2

Then split faces by script with unicode-range, so the Devanagari file downloads only when Devanagari text appears. Finally set font-display: swap shows a fallback font at once; optional uses the web font only if it arrives very quickly, so there is no late swap.

In this demo the Devanagari "file" is an empty data: placeholder, so no network request is made:

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>unicode-range demo</title>
  <style>
    /* One family, two faces. Each face is used only for its own characters. */
    @font-face {
      font-family: "Shop Sans";
      src: local("Arial"), local("Helvetica"), local("Liberation Sans"), local("DejaVu Sans");
      unicode-range: U+0000-00FF, U+20B9;              /* Latin and the rupee sign */
      font-display: swap;
    }
    @font-face {
      font-family: "Shop Sans";
      src: url("data:font/woff2;base64,AAAA") format("woff2");  /* stands in for devanagari-sub.woff2 */
      unicode-range: U+0900-097F, U+200C-200D, U+25CC; /* Devanagari block, ZWNJ/ZWJ, dotted circle */
      font-display: swap;
    }
    body { font-family: "Shop Sans", system-ui, sans-serif; margin: 16px; }
    .sale { font-size: 1.4rem; }
    td, th { border: 1px solid #aaa; padding: 4px 8px; text-align: left; }
    table { border-collapse: collapse; }
  </style>
</head>
<body>
  <h1>Pune Saree House</h1>
  <p class="sale" id="sale">Diwali sale: 20% off, from ₹1,299.</p>
  <button type="button" id="hindi">Add the Hindi line</button>
  <table>
    <thead><tr><th>Face (unicode-range)</th><th>Status</th></tr></thead>
    <tbody id="faces"></tbody>
  </table>
  <script>
    function report() {
      const rows = [];
      document.fonts.forEach((face) => {
        const tr = document.createElement("tr");
        for (const text of [face.unicodeRange, face.status]) {
          const td = document.createElement("td");
          td.textContent = text;
          tr.append(td);
        }
        rows.push(tr);
      });
      document.getElementById("faces").replaceChildren(...rows);
    }
    document.fonts.ready.then(report);

    document.getElementById("hindi").addEventListener("click", async () => {
      const p = document.createElement("p");
      p.className = "sale";
      p.lang = "hi";
      p.textContent = "दिवाली सेल: सभी साड़ियों पर छूट";
      document.getElementById("sale").after(p);
      await document.fonts.ready;
      report();
    });
  </script>
</body>
</html>

At first the Devanagari face says unloaded: no Devanagari text, no download. Click the button and it changes to error, which proves the browser tried to fetch it the moment Hindi text appeared. With a real subset file it would say loaded; here the text falls back to a system font, and the Console notes that the placeholder could not be decoded.

Image, third-party and caching review

Images. For each image ask: is it the size it is displayed at, in AVIF or WebP, with width and height? Is the LCP image eager, with fetchpriority="high", and every image below the fold lazy? Details are in Lazy Loading & Image Optimization.

Third-party scripts. Chat widgets, analytics, ads and embeds often cost more than your own code. Set a budget, written in the project README, for example "at most two third-party origins and 50 KB of third-party JavaScript on the home page". Give each script an owner and a reason. Replace heavy embeds with a facade: a lightweight button or image that loads the real thing on click, as in the "after" page above. Lighthouse lists these in its "3rd parties" insight.

Caching. Our "before" page also failed "Use efficient cache lifetimes", because the test server sent no Cache-Control. Check that hashed assets get a year with immutable and HTML gets no-cache, as explained in CDN & Static Asset Delivery. Run the same checks automatically on every change through CI/CD.

Common mistakes

  • Trusting one Lighthouse run. Compare medians of several runs, and confirm with field data.
  • Removing whitespace between inline elements. Words and buttons run together.
  • Inlining the whole stylesheet. Inline only critical CSS; the rest should be cached.
  • Subsetting Indic fonts without layout features. Conjuncts and vowel signs break.
  • Lazy-loading the hero image. It delays LCP, as the "before" page showed.

Interview questions

1. What is the difference between lab data and field data?

Lab data comes from a controlled test such as Lighthouse on one device and network, so it is repeatable and good for debugging. Field data, such as CrUX or the web-vitals library, comes from real visitors on real devices. Core Web Vitals assessments use field data at the 75th percentile.

2. Which whitespace must an HTML minifier keep?

Content of <pre> and <textarea>, whitespace between inline elements where it separates words or inline-block items, and whitespace inside elements styled with white-space: pre. Most minifiers handle the first two by default; the CSS case they cannot know about.

3. What is critical CSS, and what is the trade-off of inlining it?

It is the CSS needed to render the first screen. Inlining it removes a render-blocking request, so the first paint is faster. The cost is that inline CSS is downloaded with every HTML page and not cached separately, so keep it small.

4. How would you load a Devanagari web font efficiently?

Subset it to the Devanagari block plus ZWJ, ZWNJ and the dotted circle, keep all layout features, and ship WOFF2. Declare it with unicode-range so it downloads only when needed, choose a suitable font-display, and preload it only if it is used on the first screen.

5. How do you control the cost of third-party scripts?

Set a written budget for origins and bytes, give every script an owner, and remove what nobody needs. Load scripts after the page is usable, or behind a facade that loads them on interaction, and watch the third-party section of Lighthouse.

Key points

  • Measure before and after: lab data for repeatable comparisons, field data for the truth.
  • Minify HTML with safe settings; gzip already removes most of the gain.
  • Inline a small amount of critical CSS and load the rest without blocking.
  • Remove unused CSS and JavaScript, but safelist classes built in scripts.
  • Subset Indic fonts with layout features, split them with unicode-range and set font-display.
  • Put third-party scripts on a budget and use facades for heavy widgets.

Exercise

Take a page from one of your earlier projects and run a final pass. Record Lighthouse numbers three times and note the medians. Then: minify the HTML with safe settings and check the rendering, inline critical CSS, remove one unused stylesheet or script, fix the LCP image, and move one third-party widget behind a facade. Measure three times again and write a short before/after table with one sentence per change.

Show solution

A report template; fill in your own medians:

Text
Page: /index.html   Tool: Lighthouse 13.6.0, mobile defaults   Runs: 3 each (median)

Metric                     Before    After
Performance score          ...       ...
Largest Contentful Paint   ...       ...
Total Blocking Time        ...       ...
Cumulative Layout Shift    ...       ...

Changes and the metric each one should move
1. Hero image resized to WebP, width/height added, lazy removed     -> LCP
2. Critical CSS inlined, unused framework CSS removed                -> FCP, LCP
3. Chat widget behind a "Chat with us" button                        -> TBT, main-thread work
4. Banner space reserved with min-height                             -> CLS
5. Safe HTML minify (check rendering of inline text and nav)         -> transfer size, small

Naming the tool, settings and number of runs, and linking each change to a metric, makes the result easy to check and repeat.

Quick Quiz

1. Why did Total Blocking Time show 0 ms on the "before" page even though it ran a 600 ms script?

2. Which minifier option made "Hand printed in Sanganer" render as "Hand printed inSanganer"?

3. What does unicode-range on an @font-face rule do?

4. Why should inline critical CSS stay small?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call