Using client-side navigation I can navigate between pages using only JavaScript. The first request of a page takes some time to render and then the navigation back to it is nearly instant. During that first render that page only loads what’s necessary for it. That isolates each page making them independent. I just want to know, if there is a way to load the code for more than one page on a single request.
As an example, let’s say I have multiple profile pages for a user (info, settings, history). I want to load the code for all of those pages on one request for any of those pages, so the navigation between them will be instant, and there will be no waiting time.
Advertisement
Answer
As long as the links (using next/link
) to those pages are within the viewport the pages will be prefetched by default when in production mode (prefetch doesn’t work in dev mode, though).
prefetch
– Prefetch the page in the background. Defaults totrue
. Any<Link />
that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passingprefetch={false}
. Whenprefetch
is set tofalse
, prefetching will still occur on hover. Pages using Static Generation will preload JSON files with the data for faster page transitions. Prefetching is only enabled in production.
If you’re not using next/link
to navigate to those pages, then you can use router.prefetch
to force the prefetch.
router.prefetch(url, as)
url
– The URL to prefetch, including explicit routes (e.g./dashboard
) and dynamic routes (e.g./product/[id]
)as
– Optional decorator forurl
. Before Next.js 9.5.3 this was used to prefetch dynamic routes, check our previous docs to see how it worked