Skip to content

critical-script

Turn a TypeScript module into an inline script that runs before the main JS bundle to prefetch APIs, preload resources, call native webview bridges, and reduce LCP time.

critical-script runs TypeScript at the earliest point in the browser's rendering pipeline at which any code can run. Handling the API calls the first render and paint depend on in that inline script is what gets the screen up sooner.

  1. critical-script runs

    critical-script is off. The code that calls the API sits in the JavaScript bundle.

    <head>
      <script>window.__home = fetch("/api/home.json")</script>
      <script type="module" src="/app.js"></script>
    </head>
  2. API request

    The API request and its response are late by as much as the bundle takes to download and run.

  3. Hero image

    The image's URL is in that response, so the image request starts late too.

Benchmark

not loaded yet

With critical-script

not loaded yet

Without critical-script

See how quickly a page loads when critical-script handles the API request.

Simulation settingsSlow 4G · API latency 200ms · Bundle startup 200ms
Network throttling

A service worker stands in for a slow connection.

Added API latency

Adds the delay a server spends on a call of its own, calling other services or waiting on a database, before it starts sending an answer.

Bundle startup time

How long the browser spends running the JavaScript bundle once it has downloaded it. It stands in for the time a web application framework such as React spends initializing itself and rendering for the first time.