Prefetching

The goal of Qwik's prefetching is not to prefetch the entire application, but to have already prefetched and cached what's possible at that time. When the Qwik optimizer breaks apart the application, it's able to understand possible user interactions. And from this, it's just as important that it's able to understand what's not possible from user interaction.

For example, an entire rendered application may only be able to click a button, but that also means the entire app could never re-render. Since Qwik is able to understand what's possible, and not possible, it's able to best collect which bundles to prefetch.

Prefetching Per Page

Each page load will prefetch bundles that could be executed by the user. For example, let's say that the page has a click listener on a button. When the page loads, the very first thing the service worker does is ensure the bundle for that click listener is prefetched and waiting in the cache. When the user clicks the button, and Qwik makes a request to the event listener's bundle, the goal is the bundle is already sitting in the cache ready to execute.

Prefetching Per Interaction

You can think of the page load as the first user interaction, which prefetches what the next user interaction could be. When a follow-up interaction happens, such as opening a modal, then Qwik will again emit another prefetch event with additional bundles that could be used since the last interaction happened. Prefetching not only happens on page load but continuously happens as users interact with the application.

Prefetch Event

The recommended prefetching strategy is to use a service worker to populate the browser's Cache. Qwik itself should be configured to use the prefetchEvent implementation, which will dispatch a prefetch event.

The qprefetch event can contain various detailed data about what to prefetch, such as:

DataDescription
bundlesAn array of JavaScript bundle names to prefetch. A "bundle" is a collection of symbols.
symbolsAn array of symbols to prefetch. The service worker already understands which bundles each symbol is a part of.
linksExperimental: An array of link hrefs to prefetch.

Dispatching a prefetch event

Below is an example of a prefetch event being dispatched. These events are dispatched from Qwik itself and do not require developers to dispatch these events manually. Additionally, the service worker will automatically add listeners for these events.

dispatchEvent(new CustomEvent("qprefetch", { detail: {
  bundles: [...]
}}));
Made with โค๏ธ by