Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท Images and Performance

Performance: Lighthouse, Code Splitting and Prefetching

Understand how Gatsby keeps sites fast: per-page code splitting, link prefetching, Lighthouse metrics, font and script loading, and bundle analysis.

Gatsby sites are fast by default because most of the work happens at build time: pages are pre-rendered to HTML, assets get content hashes for long-term caching, and JavaScript is split per page. But defaults only go so far. Heavy images, large third-party scripts and web fonts can still ruin the numbers. This lesson explains what Gatsby does for you and what you must watch yourself.

How Gatsby makes pages fast

  1. Pre-rendered HTML. The browser can paint content before any JavaScript runs.
  2. Code splitting per page. Each page gets its own small chunk, plus a shared "framework" chunk and an "app" chunk. Visiting /about never downloads the code of /shop.
  3. Page data in JSON. The result of a page's GraphQL query is stored in page-data/<path>/page-data.json, so client-side navigation fetches a small file, not a new HTML page.
  4. Prefetching. When a <Link> from gatsby scrolls into view, Gatsby prefetches that page's chunk and its page data with low priority. Clicking then feels instant.
  5. Immutable caching. Files with a content hash in their name can be cached for a year.
flowchart LR
  A["Link enters viewport"] --> B["Prefetch page-data.json"]
  B --> C["Prefetch page chunk"]
  C --> D["Click: render from memory"]

Prefetching moves the network wait before the click.

Use Gatsby's Link for internal navigation, not a plain <a>. A plain anchor causes a full page load and skips prefetching:

JSX
// real Gatsby, read-only
import { Link } from "gatsby"

<Link to="/blog/">Blog</Link>
<Link to="/blog/" activeClassName="current" partiallyActive>Blog</Link>

Measuring with Lighthouse

Lighthouse (in Chrome DevTools, or via npx lighthouse) scores a page from 0 to 100 using weighted metrics. Always test a production build (gatsby build && gatsby serve); the development server is unoptimized and its numbers mean nothing. Use an incognito window, because extensions skew results.

Metric Meaning Weight (Lighthouse 10)
First Contentful Paint First text or image appears 10%
Speed Index How quickly the page fills in 10%
Largest Contentful Paint Biggest element is visible 25%
Total Blocking Time Main thread busy time 30%
Cumulative Layout Shift Unexpected movement 25%
JS Stand-in: a weighted performance score

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The weights explain why blocking time and layout shift deserve attention: together they are more than half of the score.

Typical problems and fixes

  • Slow LCP: the hero image is lazy-loaded or unoptimized. Use loading="eager" and a sensible width (see StaticImage).
  • Layout shift: images without reserved space or late-loading fonts. Use the image components, and set font-display: swap.
  • Blocking time: too much JavaScript. Look for big dependencies you can replace.
  • Third-party scripts: analytics and chat widgets. Load them with the Script component.
JSX
// real Gatsby, read-only
import { Script } from "gatsby"

<Script src="https://example.com/analytics.js" strategy="post-hydrate" />

Script has three strategies: post-hydrate (after the page is interactive), idle (when the browser is idle) and off-main-thread (runs in a web worker through Partytown, experimental). The default Script behavior keeps third parties off the critical path.

Fonts

Self-host fonts (for example with @fontsource packages) instead of loading them from a third-party domain; that removes a connection and gives you control. Import only the weights you use, and preload the one used above the fold.

Looking inside the bundle

gatsby build --profile and plugins such as gatsby-plugin-webpack-bundle-analyser-v2 produce a treemap of what each chunk contains. Typical findings: a whole icon library imported for three icons, moment with all locales, or a charting library loaded on every page. Fix by importing from specific paths, using a lighter library, or loading heavy components lazily:

JSX
// real React, read-only
const Chart = React.lazy(() => import("../components/chart"))
// <React.Suspense fallback={<p>Loading chart...</p>}><Chart /></React.Suspense>

Note that React.lazy is for client-side only code; guard it for the server render (Gatsby renders on the server at build time) with a typeof window check or a "mounted" state, or use @loadable/component.

Simulating prefetch order

The stand-in below models a prefetch queue where links nearer the top are fetched first and the browser limits parallel requests. It is only a teaching model.

JS Stand-in: a prefetch queue

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you run Lighthouse on a production build?

    gatsby develop does not minify or split like gatsby build, so measure gatsby build plus gatsby serve.
  2. 2. What does the Link component from gatsby do that a plain anchor does not?

    Visible Links trigger low-priority prefetching, and navigation happens client-side.
  3. 3. Which Script strategy runs a script after the page is interactive?

    post-hydrate delays the script until hydration completes; idle and off-main-thread are the other options.
  4. 4. Which two metrics carry the most weight in the Lighthouse 10 performance score?

    TBT counts 30%, LCP and CLS 25% each.

Summary

  • Gatsby pre-renders pages, splits code per page, prefetches linked pages and caches hashed files.
  • Use Link for internal navigation and measure production builds.
  • Fix LCP with eager hero images, CLS with reserved space, TBT by trimming JavaScript.
  • Use Script to keep third-party code off the critical path; self-host fonts.
  • Analyze the bundle before guessing.

Next: Markdown blog pages with remark