Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Performance and Lighthouse

Loading and Resource Hints

Speed up loading in a PWA: preload, preconnect, prefetch, modulepreload, fetchpriority, lazy images, code splitting, font loading and yielding long tasks.

Browsers load pages by discovering resources as they parse: HTML first, then CSS, then the scripts and images those mention. Discovery order is not the same as importance order. Resource hints let you tell the browser what matters sooner, and loading strategies let you send less code up front. Together they are the most reliable way to improve LCP and interactivity for the first visit, the one a service worker cannot help with.

The hints, one by one

Hint When to use Example
preconnect You will fetch from another origin very soon <link rel="preconnect" href="https://cdn.example.com" crossorigin>
dns-prefetch Cheaper fallback to preconnect for less important origins <link rel="dns-prefetch" href="https://analytics.example">
preload A resource the current page needs but the parser finds late <link rel="preload" as="image" href="/hero.avif" fetchpriority="high">
modulepreload An ES module (and its dependencies) needed soon <link rel="modulepreload" href="/js/app.js">
prefetch A resource for a likely next page, loaded at low priority <link rel="prefetch" href="/articles.js">

Rules of thumb:

  • preconnect costs a socket and a TLS handshake, so use it for two or three origins at most.
  • preload needs the right as value (script, style, font, image, fetch) or the browser fetches it twice. Fonts also need crossorigin, even from your own domain.
  • Do not preload everything. Preloading competes with other resources, and over-preloading makes the page slower.
  • prefetch is a hint, not a promise: the browser may ignore it on slow connections or when Data Saver is on.

Priority hints

Images and scripts get a priority from the browser. fetchpriority lets you adjust it:

HTML
<img src="/hero.avif" width="1200" height="600" fetchpriority="high" alt="...">
<img src="/below-the-fold.avif" width="600" height="300" loading="lazy" fetchpriority="low" alt="...">

Mark the one image that is your LCP element as high. Never mark every image high, or the hint means nothing. Also avoid loading="lazy" on the LCP image; lazy images wait for layout and start later.

Try it: choosing the right hint

A function can encode the decision, which makes a good review checklist for your pages:

JS Which hint fits?

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

No output.

Code splitting

Users should download only the code for the screen they see. With dynamic import(), bundlers (Vite, webpack, Rollup, esbuild) create a separate file per imported module:

JavaScript
// read-only: bundler splits ./chart.js into its own file
button.addEventListener("click", async () => {
  const { drawChart } = await import("./chart.js");
  drawChart(data);
});

Split by route first (each page is a chunk), then by heavy feature (charts, editors, maps, PDF export). Combine it with hints: preload the chunk when the user hovers a button, so the click feels instant.

JS Lazy loading a feature on demand

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

No output.

Caching the promise (not the result) is the trick: two quick calls share one download.

Images and fonts

Images are usually the heaviest bytes:

  • Use srcset and sizes so phones do not download desktop images.
  • Prefer AVIF or WebP with a JPEG fallback in <picture>.
  • Always set width and height (or CSS aspect-ratio) to reserve space and keep CLS near zero.
  • Give a hero image fetchpriority="high" and everything below the fold loading="lazy".

Fonts cause invisible or jumping text:

CSS
@font-face {
  font-family: "Inter";
  src: url("/fonts/inter-var.woff2") format("woff2");
  font-display: swap;
}

font-display: swap shows fallback text immediately. Self-host the font (one fewer origin), subset it to the characters you use, and preload only the one file the first view needs.

Keep the main thread free

INP and TBT suffer when a single task runs for more than 50 ms. Break long loops into chunks and let the browser handle input in between:

JavaScript
// modern browsers: await scheduler.yield();  fallback: setTimeout 0
const yieldToMain = () =>
  globalThis.scheduler?.yield?.() ?? new Promise((resolve) => setTimeout(resolve, 0));
JS Process in chunks, stay responsive

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

No output.

Move truly heavy computation to a Web Worker so it never touches the main thread.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which hint is for a resource needed by the NEXT page, at low priority?

    prefetch is a low-priority hint for likely future navigations.
  2. 2. Why should the LCP image not have loading="lazy"?

    Lazy images wait until layout shows they are near the viewport; the LCP image should start as early as possible.
  3. 3. What problem does font-display: swap address?

    swap renders fallback text right away and swaps when the web font arrives.
  4. 4. Why cache the promise of a lazy import instead of its result?

    If two callers ask before the first finishes, they both receive the same pending promise.

Summary

  • Use preconnect, preload, modulepreload and prefetch sparingly and with the right as/crossorigin.
  • Raise the priority of the LCP image only; lazy load what is below the fold.
  • Split code by route and heavy feature; start loading on hover or idle.
  • Optimize images and fonts, reserve space to avoid layout shifts.
  • Yield during long tasks or move work into a worker.

Next: The Install Prompt