Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Next.js prefetching should use requestIdleCallback #14580

Merged
merged 6 commits into from
Jul 28, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions packages/next/client/page-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ const relPrefetch =

const hasNoModule = 'noModule' in document.createElement('script')

const requestIdleCallback =
window.requestIdleCallback ||
function (cb) {
return setTimeout(cb, 1)
}

/** @param {string} route */
function normalizeRoute(route) {
if (route[0] !== '/') {
Expand Down Expand Up @@ -178,19 +184,20 @@ export default class PageLoader {
prefetchData(href, asPath) {
const { pathname: hrefPathname } = parse(href, true)
const route = normalizeRoute(hrefPathname)
return this.promisedSsgManifest.then(
(s, _dataHref) =>
return this.promisedSsgManifest.then((s, _dataHref) => {
requestIdleCallback(() => {
// Check if the route requires a data file
s.has(route) &&
// Try to generate data href, noop when falsy
(_dataHref = this.getDataHref(href, asPath, true)) &&
// noop when data has already been prefetched (dedupe)
!document.querySelector(
`link[rel="${relPrefetch}"][href^="${_dataHref}"]`
) &&
// Inject the `<link rel=prefetch>` tag for above computed `href`.
appendLink(_dataHref, relPrefetch, 'fetch')
)
// Try to generate data href, noop when falsy
(_dataHref = this.getDataHref(href, asPath, true)) &&
// noop when data has already been prefetched (dedupe)
!document.querySelector(
`link[rel="${relPrefetch}"][href^="${_dataHref}"]`
) &&
// Inject the `<link rel=prefetch>` tag for above computed `href`.
appendLink(_dataHref, relPrefetch, 'fetch')
})
})
}

loadPage(route) {
Expand Down