EthicsComputerCourses
Join training +91 90532 10052

Critical Rendering Path

HTML · Lesson 125 of 234 Advanced 12 min read Updated

By the end of this lesson you will be able to find the resources that delay a page's first paint, remove or shrink them with critical CSS, media attributes, defer and font-display, and prove the improvement with the Performance panel and the Navigation, Resource and Paint Timing APIs.

What you should know first: Browser Rendering Fundamentals, Browser Rendering Pipeline, Script Loading: Async & Defer and Resource Hints: Preload, Prefetch & Preconnect.

What the critical rendering path is

The critical rendering path is the minimum work a browser must finish before it can paint the first pixels of a page: download the HTML, build the DOM, download and parse the CSS that blocks rendering, build the render tree, lay out and paint.

A shop in Lucknow cannot raise its shutter until the signboard and price labels are up. The HTML and render-blocking CSS are those; images and analytics can arrive after the shutter is up.

Three numbers describe a page's critical path:

  • Critical resources: files that can block the first paint (render-blocking CSS, parser-blocking scripts).
  • Critical path length: how many round trips to the server are needed in sequence. A CSS file that @imports another file adds a round trip.
  • Critical bytes: the total size of those files.

Reducing all three brings First Contentful Paint and Largest Contentful Paint earlier, as Core Web Vitals Fundamentals explains.

Render-blocking CSS

A <link rel="stylesheet"> in the head is render-blocking: nothing is painted until it is downloaded and parsed. The media attribute changes this. Every stylesheet is still downloaded, but one whose media query does not match right now is fetched at low priority and does not block:

HTML
<link rel="stylesheet" href="/css/base.css">                                  <!-- blocks -->
<link rel="stylesheet" href="/css/print.css" media="print">                   <!-- does not block on screen -->
<link rel="stylesheet" href="/css/wide.css" media="(min-width: 64em)">        <!-- blocks only on wide screens -->
<link rel="stylesheet" href="/css/dark.css" media="(prefers-color-scheme: dark)">

Avoid @import in CSS: the imported file is discovered only after the first is parsed, adding a round trip.

The opposite tool also exists: blocking="render" on a <link>, <script> or <style> makes a resource render-blocking on purpose. It works in Chromium browsers and Safari 18.2+, not yet in Firefox.

Parser-blocking JavaScript, and the CSS trap

A classic <script> without defer, async or type="module" is parser-blocking: the parser stops until the script has downloaded and run. Script Loading: Async & Defer covers this in full.

The trap: a classic script may read styles, so the browser will not run it until every stylesheet above it has loaded. This applies to inline scripts too:

HTML
<head>
  <link rel="stylesheet" href="/css/site.css">   <!-- takes 800 ms on 4G -->
  <script>
    // Tiny inline snippet, but it must wait for site.css,
    // and the parser waits for it. Nothing below is even parsed.
    document.documentElement.classList.add("js");
  </script>
</head>

Two fixes: move small inline scripts that do not need styles above the stylesheet, or turn them into deferred or module scripts.

Critical CSS inlining

Critical CSS is the small set of rules needed for the first screen: header, navigation, hero and the first text. Inlined in a <style> element, it lets the first paint happen without any stylesheet download. The full stylesheet then loads without blocking:

HTML
<head>
  <style>
    /* critical: header, hero and first section only */
    body { margin: 0; font-family: system-ui, sans-serif; }
    .site-header { display: flex; justify-content: space-between; padding: 1rem; background: #7c2d12; color: white; }
    .hero { min-height: 60vh; display: grid; place-items: center; }
  </style>
  <link rel="preload" href="/css/site.css" as="style">
  <link rel="stylesheet" href="/css/site.css" media="print" onload="this.media='all'">
  <noscript><link rel="stylesheet" href="/css/site.css"></noscript>
</head>

The media="print" trick downloads without blocking, then switches to all media on load; <noscript> covers visitors without JavaScript. If your Content Security Policy forbids inline handlers, attach onload from a script file.

The trade-off: inline CSS is downloaded with every page, while an external file is cached once. Keep it to a few kilobytes; a common target is fitting the first screen's HTML and CSS in about 14 KB compressed. Build tools can extract it, but check the result at phone and laptop widths.

Fonts and font-display

Web fonts join late: the browser finds a font only after parsing the CSS and meeting text that uses it. While it downloads, text is hidden or shown in a fallback font. The font-display descriptor in @font-face chooses:

ValueBlock period (text invisible)Swap period (font may still replace the fallback)
autoBrowser decides, usually like blockBrowser decides
blockShort, about 3 s recommendedInfinite
swapExtremely small, 100 ms or less recommendedInfinite
fallbackExtremely smallShort, about 3 s recommended
optionalExtremely smallNone: if the font is not ready, the fallback stays

The durations are the CSS Fonts specification's recommendations. Hidden text is called FOIT (flash of invisible text); fallback text that changes is FOUT (flash of unstyled text).

CSS
@font-face {
  font-family: "Mukta";
  src: url("/fonts/mukta-500.woff2") format("woff2");
  font-weight: 500;
  font-display: swap;   /* show text at once, swap in Mukta when it arrives */
}

Use swap for brand headings that must use the font eventually, and optional for body text where a stable layout matters more. Preload the one or two fonts the first screen needs with <link rel="preload" as="font" type="font/woff2" crossorigin>, and self-host fonts where you can, so no extra connection is needed.

Measuring the path

The Performance panel

  1. Open the page in Chrome, press F12 and open Performance.
  2. Set CPU throttling to 4x and network to a slow 4G preset.
  3. Click Record and reload.
  4. In the Network track, render-blocking requests carry a small red triangle in their upper right corner. Click one: the Summary says whether it was render-blocking and shows its priority.
  5. Look at the markers for FCP and LCP in the timings, and open the Insights tab for suggestions about render-blocking requests and fonts.

The timing APIs

The same data is available to JavaScript through the Performance Timeline. performance.getEntriesByType(type) returns a list of entries:

TypeEntryUseful fields
"navigation"One PerformanceNavigationTiming for the pageresponseStart (first byte), domInteractive, domContentLoadedEventStart, loadEventStart, type, nextHopProtocol
"resource"One PerformanceResourceTiming per filename, initiatorType, duration, transferSize (often 0 from the cache), renderBlockingStatus (Chromium only)
"paint"first-paint and first-contentful-paintstartTime

Times are milliseconds from the start of the navigation.

Step 1: read the timelines

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Reading the timelines</title>
  <style>
    body { font-family: sans-serif; padding: 1rem; }
    img { width: 160px; height: auto; }
    pre { background: #f4f4f4; padding: 8px; overflow-x: auto; }
  </style>
</head>
<body>
  <h1>Jaipur Handicrafts</h1>
  <img src="https://course.ethicscomputer.in/assets/samples/landscape.svg" alt="Blue pottery display" width="800" height="500">
  <img src="https://course.ethicscomputer.in/assets/samples/logo.svg" alt="Shop logo" width="240" height="80">
  <pre id="out">Waiting for the load event...</pre>

  <script>
    function navigationReport(win, label) {
      const nav = win.performance.getEntriesByType("navigation")[0];
      if (!nav) return label + ": no navigation entry\n";
      const ms = (value) => value.toFixed(0).padStart(6) + " ms";
      return label + " (" + nav.type + ", " + (nav.nextHopProtocol || "no network") + ")\n" +
        "  first byte (responseStart) " + ms(nav.responseStart) + "\n" +
        "  domInteractive             " + ms(nav.domInteractive) + "\n" +
        "  DOMContentLoaded start     " + ms(nav.domContentLoadedEventStart) + "\n" +
        "  load event start           " + ms(nav.loadEventStart) + "\n";
    }

    window.addEventListener("load", () => {
      // Wait a moment: loadEventEnd and the paint entries are filled in after the load handlers run.
      setTimeout(() => {
        let text = navigationReport(window, "This demo page");

        // The editor runs this page inside its own page. If we may read it, show its real network timing.
        try {
          if (window.parent !== window) text += "\n" + navigationReport(window.parent, "The editor page around it");
        } catch (error) {
          text += "\n(The surrounding page is not readable from here.)\n";
        }

        text += "\nResources loaded by this page:\n";
        for (const entry of performance.getEntriesByType("resource")) {
          const file = entry.name.split("/").pop();
          text += "  " + file.padEnd(16) + entry.initiatorType.padEnd(6) +
            entry.duration.toFixed(0).padStart(5) + " ms  " +
            entry.transferSize + " bytes over the network" +
            ("renderBlockingStatus" in entry ? "  (" + entry.renderBlockingStatus + ")" : "") + "\n";
        }

        text += "\nPaint entries:\n";
        for (const entry of performance.getEntriesByType("paint")) {
          text += "  " + entry.name.padEnd(24) + entry.startTime.toFixed(0) + " ms\n";
        }
        document.querySelector("#out").textContent = text;
      }, 1000);
    });
  </script>
</body>
</html>

The first block describes this demo page. The editor runs your code in a frame created from text, so its network fields are zero, but domInteractive and the load event still show how long parsing took. The second block reads the editor page around it, a real network navigation with a real time to first byte. The resource list shows the two sample images, each with (non-blocking) in Chromium browsers, and the paint list shows when the frame first painted. Run it twice: the second time, transferSize may drop to 0 because the images come from the cache.

Before and after: optimising a real head

Here is the head of a handicrafts shop page in Jaipur, before any work:

HTML
<head>
  <meta charset="utf-8">
  <title>Jaipur Handicrafts | Blue pottery</title>
  <link rel="stylesheet" href="https://fonts.example.com/css?family=Mukta">  <!-- 1 -->
  <link rel="stylesheet" href="/css/all.css">        <!-- 2: 180 KB, @imports theme.css -->
  <script src="/js/jquery.js"></script>              <!-- 3 -->
  <script src="/js/slider.js"></script>              <!-- 4 -->
  <script>dataLayer.push({ page: "pottery" });</script>  <!-- 5: waits for 1 and 2 -->
</head>
<body>
  <div class="hero" style="background-image: url(/img/pottery.jpg)"></div>  <!-- 6 -->

The problems, in critical path terms:

  1. A font stylesheet from another server: a new connection, then a render-blocking file, then the font itself.
  2. One big render-blocking stylesheet whose @import adds another round trip.
  3. and 4. Two parser-blocking scripts that also wait for the CSS above them.
  4. An inline script that waits for all the CSS before the parser can continue.
  5. The hero image hidden in an inline style, invisible to the preload scanner, so the main content paints late.

Critical resources: 5 files. Critical path length: about 4 round trips in sequence. The optimised head:

HTML
<head>
  <meta charset="utf-8">
  <title>Jaipur Handicrafts | Blue pottery</title>
  <script>window.dataLayer = [{ page: "pottery" }];</script>      <!-- above the CSS: no wait -->
  <link rel="preload" href="/fonts/mukta-500.woff2" as="font" type="font/woff2" crossorigin>
  <style>
    @font-face { font-family: "Mukta"; src: url("/fonts/mukta-500.woff2") format("woff2");
                 font-weight: 500; font-display: swap; }
    /* about 4 KB of critical CSS for header, hero and first products */
  </style>
  <link rel="stylesheet" href="/css/products.css" media="print" onload="this.media='all'">
  <script src="/js/slider.js" defer></script>
</head>
<body>
  <img class="hero" src="/img/pottery.jpg" alt="Blue pottery vases from Jaipur"
       width="1200" height="600" fetchpriority="high">

Critical resources: only the HTML. The font is self-hosted and preloaded, the rest of the CSS loads without blocking, jQuery is gone (the slider was rewritten without it), the slider is deferred, and the hero is a real <img> that the preload scanner finds at once.

Step 2: measure a before and after yourself

You cannot slow down a real network inside the editor, but you can reproduce the main-thread side of the problem. This demo loads two tiny pages into frames. Both do 800 ms of script work. In "before", the work runs in a classic script in the head, as a big blocking script would. In "after", a module script waits until the first frame has painted, using requestAnimationFrame and then setTimeout, before doing the same work.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Before and after</title>
  <style>
    body { font-family: sans-serif; padding: 1rem; }
    iframe { width: 100%; height: 90px; border: 1px solid #999; }
    pre { background: #f4f4f4; padding: 8px; }
  </style>
</head>
<body>
  <h1>Kochi Spice Market: two versions of one page</h1>
  <p>Both pages do 800 ms of script work. Only the place of that work changes.</p>
  <button id="run">Load both pages</button>
  <iframe id="before" title="Before: blocking script in the head"></iframe>
  <iframe id="after" title="After: work moved after the first paint"></iframe>
  <pre id="out"></pre>

  <script>
    // Stands in for a big classic script: it keeps the main thread busy.
    const busy = "function busy(ms) { const end = performance.now() + ms; while (performance.now() < end) {} }";

    const before = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Before</title>
      <script>${busy} busy(800);<\/script></head>
      <body><h2>Fresh pepper, ₹650 per kg</h2></body></html>`;

    const after = `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>After</title>
      <script type="module">${busy} requestAnimationFrame(() => setTimeout(() => busy(800), 0));<\/script></head>
      <body><h2>Fresh pepper, ₹650 per kg</h2></body></html>`;

    function report(id) {
      const win = document.getElementById(id).contentWindow;
      const nav = win.performance.getEntriesByType("navigation")[0];
      const fcp = win.performance.getEntriesByName("first-contentful-paint")[0];
      return id.padEnd(7) +
        "  DOMContentLoaded " + nav.domContentLoadedEventStart.toFixed(0).padStart(4) + " ms" +
        "  first contentful paint " + (fcp ? fcp.startTime.toFixed(0).padStart(4) + " ms" : "not reported");
    }

    function load(id, html) {
      return new Promise((resolve) => {
        const frame = document.getElementById(id);
        frame.onload = () => setTimeout(resolve, 1200);
        frame.srcdoc = html;
      });
    }

    document.querySelector("#run").addEventListener("click", async () => {
      const out = document.querySelector("#out");
      out.textContent = "Loading...";
      await load("before", before);
      await load("after", after);
      out.textContent = report("before") + "\n" + report("after");
    });
  </script>
</body>
</html>
Output
before   DOMContentLoaded  835 ms  first contentful paint  892 ms
after    DOMContentLoaded   18 ms  first contentful paint   60 ms

That was our run in headless Chrome; your numbers will differ. The same 800 ms of work is done in both pages. Only its place on the critical path changed, and the price list appears about 800 ms sooner.

Common mistakes

  • One large stylesheet for the whole site. Split it, inline the critical part and load the rest without blocking.
  • @import in CSS. It adds a round trip; use <link> tags or a build step.
  • Inline scripts below stylesheets. They wait for the CSS and block the parser.
  • Fonts with no font-display. Text can stay invisible for up to about 3 seconds.
  • Preloading everything. Preloads compete for bandwidth; preload only what the first screen needs.
  • Measuring only on a fast laptop. Use CPU and network throttling.

Interview questions

1. What is the critical rendering path?

It is the sequence of work needed before the first paint: fetching the HTML, building the DOM, fetching and parsing render-blocking CSS, building the render tree, layout and paint. Optimising it means fewer critical resources, fewer round trips in sequence and fewer critical bytes.

2. Why is CSS render-blocking, and how does the media attribute help?

Browsers do not paint until stylesheets in the head are loaded, to avoid a flash of unstyled content. A stylesheet whose media query does not match is still downloaded, at low priority, but does not block rendering.

3. Why can an inline script slow down the first paint?

A classic script, even inline, must wait for every stylesheet above it, because it might read styles. While it waits, the parser is blocked. Placing small inline scripts before the stylesheets avoids this.

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

It is the CSS needed for the first screen, inlined in a <style> element so the first paint needs no stylesheet download. The trade-off is that inline CSS is not cached separately and is downloaded with every page, so it must stay small.

5. Compare font-display: swap and font-display: optional.

swap shows fallback text almost immediately and replaces it whenever the font arrives, which can shift the layout. optional uses the font only if it is ready almost at once; otherwise the fallback stays for that page view, which keeps the layout stable.

Key points

  • The critical rendering path is the work before the first paint; shorten it by cutting critical resources, round trips and bytes.
  • Head stylesheets block rendering; non-matching media stylesheets do not.
  • Classic scripts block parsing and wait for earlier CSS, even when inline.
  • Inline small critical CSS, then load the full stylesheet without blocking.
  • Use font-display and preload the few fonts the first screen needs.
  • Measure with the Performance panel and performance.getEntriesByType() for navigation, resource and paint entries.

Exercise

Isha's coaching institute page in Rohtak has this head: a Google-hosted font stylesheet, site.css (120 KB, of which the first screen needs about 3 KB), print.css without a media attribute, an inline script that sets a theme class, and a classic analytics.js. Rewrite the head to shorten the critical path, and add a small script that, after the page loads, prints the time to first byte, domInteractive and the first contentful paint from the timing APIs.

Show solution
HTML
<head>
  <meta charset="utf-8">
  <title>Rohtak Science Classes | Admissions open</title>
  <script>document.documentElement.classList.add(localStorage.getItem("demo-theme") || "light");</script>
  <link rel="preload" href="/fonts/hind-400.woff2" as="font" type="font/woff2" crossorigin>
  <style>
    @font-face { font-family: "Hind"; src: url("/fonts/hind-400.woff2") format("woff2"); font-display: swap; }
    /* about 3 KB of critical CSS for the header, hero and admission form */
  </style>
  <link rel="stylesheet" href="/css/site.css" media="print" onload="this.media='all'">
  <noscript><link rel="stylesheet" href="/css/site.css"></noscript>
  <link rel="stylesheet" href="/css/print.css" media="print">
  <script src="/js/analytics.js" async></script>
  <script type="module">
    addEventListener("load", () => setTimeout(() => {
      const nav = performance.getEntriesByType("navigation")[0];
      const fcp = performance.getEntriesByName("first-contentful-paint")[0];
      console.log("First byte:", Math.round(nav.responseStart), "ms");
      console.log("DOM interactive:", Math.round(nav.domInteractive), "ms");
      console.log("FCP:", fcp ? Math.round(fcp.startTime) + " ms" : "not reported");
    }, 1000));
  </script>
</head>

The theme script runs before any CSS, so it does not wait. The font is self-hosted with swap, only critical CSS blocks the first paint, print.css no longer blocks the screen, and analytics is async because it does not depend on the page.

Quick Quiz

1. Which stylesheet does NOT block rendering on a phone screen?

2. An inline <script> comes after a slow stylesheet in the head. What happens?

3. Which font-display value never swaps in a font that arrives late?

4. Which call returns domInteractive and responseStart for the current page?

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