Skip to content
PrefetchView the code for this module.

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 sveltekit:prefetch like this.

<a sveltekit:prefetch href="/product/cup">

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 on our product page. 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 routes to that page, the page will load almost instantaneously.

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. To really show the difference it makes, let's add a one second time out to our load function. Now we know that it will take at least a second to fetch the products data. If we temporarily remove prefetch from the link, we see that when we click a product it lags before routing to the page. This is because the page will not render until it receives a response from the load function. Now if we add our prefetch attribute back to our link and test this again, we now see that when we click a product, we route to the page almost instantaneously.

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.