Prefetch

In this module, we will learn how to prefetch data before routing to the page to make our app feel extra snappy.
Table of Contents
Course Version History
  • Nov. 21, 2022 - Updated to SvelteKit v1.0.0-next.549. Prefetch attribute changed from sveltekit:prefetch to data-sveltekit-prefetch.

SvelteKit uses code-splitting to break up your app into small chunks of code, one per route. This ensures fast startup times since your app only has to load the code that you currently need. We can ensure even faster startup times by using SvelteKit's prefetch anchor on link tags. This prefetches the code for a page before you actually route to it.

For example, let's look at our dynamic route /product/cup. In order to render this page, we need to fetch the product's data, which we can't do until we know the product's name. This may result in a lag as the browser waits for the data to come back from the server, especially if we're fetching a lot of data. We can mitigate this delay by prefetching the data.

In our GridTile component, we can add a prefetch attribute by typing data-sveltekit-prefetch like this.

<a data-sveltekit-prefetch href="/product/cup">
  Cup
</a>

This attribute will cause SvelteKit to run the page's load function as soon as the user hovers over the link (on a desktop) or touches it (on mobile), rather than waiting for the click event to trigger navigation.

To visualize this, we can log our product value in the load function from our /product/[name]/+page.js file. Now back in our app, we will see when we hover over a product, the data for that product is being logged in the console. This is because the page's data is now being prefetched. This means that if the user then navigates to that page, the page will load almost instantaneously.

We can even apply this behaviour across the board by adding the attribute to a parent element. In our root layout we can add data-sveltekit-prefetch to the outermost div, and now every page will be pre-fetched.

Typically, prefetching buys us an extra couple of hundred milliseconds, which is the difference between a user interface that feels laggy, and one that feels snappy.

Prefetching helps make your app feel snappy. Now that we have a product built out that feels fast and looks good, let's learn how to deploy it to Vercel using adapters in the next module.