Skip to content

Commit c099530

Browse files
authored
Prefetch links nearest the top of the document first (#95393)
### Why Most viewport prefetches are scheduled via a shared `IntersectionObserver`. When several links enter the viewport at once (e.g. on initial load), the observer reports them in document order and we scheduled them in that order. Because the prefetch scheduler gives the highest priority to the *most recently scheduled* task, this meant the link **lowest** in the document ended up with the highest priority — the opposite of a sensible default. ### What Iterate each observer batch in reverse, so the link nearest the **top** of the document is scheduled last and therefore prioritized. The topmost link isn't guaranteed to be the most important, but as a default heuristic it's more reasonable than favoring whichever link happens to be lowest in the document. Also updates the two hover tests in `prefetch-scheduling`, whose expected ordering was coupled to the old bottom-first default (the set of route trees prefetched within the concurrency limit flips from pages 7,6,5,4 to 1,2,3,4). The behaviors they assert are unchanged, and a new test covers the top-of-document prioritization. --- Supersedes #94902, which was opened from a fork. The "Test new and changed tests when deployed" jobs cannot pass on fork PRs — `vercel link` fails with "No existing credentials found" because `secrets.VERCEL_ADAPTER_TEST_TOKEN` is not available to `pull_request` runs from forks. This PR is the same change (rebased onto latest canary) on an upstream branch so the deploy jobs get credentials. <!-- NEXT_JS_LLM_PR -->
1 parent 27e225f commit c099530

7 files changed

Lines changed: 105 additions & 32 deletions

File tree

‎packages/next/src/client/components/links.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,16 @@ export function unmountPrefetchableInstance(element: Element) {
247247
}
248248

249249
function handleIntersect(entries: Array<IntersectionObserverEntry>) {
250-
for (const entry of entries) {
250+
// Process the entries in reverse order. The prefetch scheduler assigns the
251+
// highest priority to the most recently scheduled task, so whichever link we
252+
// schedule *last* wins. When multiple links enter the viewport at once (e.g.
253+
// on initial load), the observer reports them in document order, so iterating
254+
// in reverse means the link nearest the top of the document is scheduled last
255+
// and therefore prioritized. The topmost link isn't guaranteed to be the most
256+
// important, but as a default heuristic it's more reasonable than prioritizing
257+
// whichever link happens to be lowest in the document.
258+
for (let i = entries.length - 1; i >= 0; i--) {
259+
const entry = entries[i]
251260
// Some extremely old browsers or polyfills don't reliably support
252261
// isIntersecting so we check intersectionRatio instead. (Do we care? Not
253262
// really. But whatever this is fine.)

‎test/e2e/app-dir/parallel-routes-breadcrumbs/app/[artist]/page.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import Link from 'next/link'
22

33
export default async function Page({ params }) {
4-
const albums = ['album1', 'album2', 'album3']
4+
// Link order affects prefetch priority: viewport prefetches are scheduled so
5+
// that links nearest the top of the document are prefetched first.
6+
const albums = ['album3', 'album2', 'album1']
57
const { artist } = await params
68
return (
79
<div>

‎test/e2e/app-dir/parallel-routes-breadcrumbs/app/page.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import Link from 'next/link'
22

33
export default async function Home() {
4-
const artists = ['artist1', 'artist2', 'artist3']
4+
// Link order affects prefetch priority: viewport prefetches are scheduled so
5+
// that links nearest the top of the document are prefetched first.
6+
const artists = ['artist3', 'artist2', 'artist1']
57
return (
68
<div>
79
<h1>Artists</h1>

‎test/e2e/app-dir/parallel-routes-root-param-dynamic-child/parallel-routes-root-param-dynamic-child.test.ts‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -175,13 +175,23 @@ describe('parallel-routes-root-param-dynamic-child', () => {
175175
it.each(['en', 'fr'])(
176176
'should render a 404 for /%s/gsp/stories/dynamic-123 (slug not in generateStaticParams)',
177177
async (locale) => {
178-
const { browser, act } = await createBrowserActor(`/${locale}`)
179-
180-
await act(async () => {
181-
await browser
182-
.elementByCss(`[href="/${locale}/gsp/stories/dynamic-123"]`)
183-
.click()
178+
// Navigate from a valid locale page to a slug that isn't in
179+
// generateStaticParams and assert the client renders the 404.
180+
//
181+
// We deliberately don't use `createRouterAct` here. The page eagerly
182+
// prefetches its sibling nav links — several of which are themselves
183+
// 404 routes — so the prefetch network doesn't reliably go idle.
184+
// Wrapping the navigation in `act` (which waits for a quiet network)
185+
// would time out. This test only cares about the rendered result,
186+
// not the prefetch traffic.
187+
const browser = await next.browser(`/${locale}`, {
188+
cpuThrottleRate: 6,
184189
})
190+
await browser.elementByCss('#reveal').click()
191+
await browser.elementByCss('#nav')
192+
await browser
193+
.elementByCss(`[href="/${locale}/gsp/stories/dynamic-123"]`)
194+
.click()
185195

186196
await retry(async () => {
187197
expect(await browser.elementByCss('.next-error-h1').text()).toBe(

‎test/e2e/app-dir/searchparams-reuse-loading/app/with-middleware/page.tsx‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,30 @@
11
import Link from 'next/link'
22

33
export default function Page() {
4+
// Link order is significant: viewport prefetches are prioritized by document
5+
// order (links nearest the top are prefetched first). The full-prefetch links
6+
// are listed first so they win priority and complete their full prefetch
7+
// before the auto-prefetch links resolve the middleware redirect.
48
return (
59
<ul>
610
<li>
7-
<Link href="/with-middleware/search-params?id=1">
8-
/search-params?id=1
11+
<Link href="/with-middleware/search-params" prefetch={true}>
12+
/search-params (prefetch: true)
913
</Link>
1014
</li>
1115
<li>
12-
<Link href="/with-middleware/search-params?id=2">
13-
/search-params?id=2
16+
<Link href="/with-middleware/search-params?id=3" prefetch={true}>
17+
/search-params?id=3 (prefetch: true)
1418
</Link>
1519
</li>
1620
<li>
17-
<Link href="/with-middleware/search-params?id=3" prefetch={true}>
18-
/search-params?id=3 (prefetch: true)
21+
<Link href="/with-middleware/search-params?id=2">
22+
/search-params?id=2
1923
</Link>
2024
</li>
2125
<li>
22-
<Link href="/with-middleware/search-params" prefetch={true}>
23-
/search-params (prefetch: true)
26+
<Link href="/with-middleware/search-params?id=1">
27+
/search-params?id=1
2428
</Link>
2529
</li>
2630
</ul>

‎test/e2e/app-dir/segment-cache/memory-pressure/app/memory-pressure/page.tsx‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,13 @@ function Tab1() {
1212
}
1313

1414
function Tab2() {
15+
// Link order is significant: viewport prefetches are prioritized by document
16+
// order (links nearest the top are prefetched first). Generate the links in
17+
// descending order so that, combined with that prioritization, the prefetch
18+
// scheduling order this test's LRU-eviction assertions depend on is
19+
// preserved.
1520
const links = []
16-
for (let i = 1; i < 60; i++) {
21+
for (let i = 59; i >= 1; i--) {
1722
links.push(<Link href={'/memory-pressure/' + i}>Link {i}</Link>)
1823
}
1924
return links

‎test/e2e/app-dir/segment-cache/prefetch-scheduling/prefetch-scheduling.test.ts‎

Lines changed: 55 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -30,27 +30,62 @@ describe('segment cache prefetch scheduling', () => {
3030
await checkbox.click()
3131
}, 'block')
3232

33-
// Hover over a link to increase its relative priority.
33+
// Hover over a link near the bottom of the document to increase its
34+
// relative priority. By default the scheduler prioritizes the links
35+
// nearest the top, so this link's route tree has not been prefetched
36+
// yet; hovering bumps it ahead of the default tasks.
37+
const link6 = await browser.elementByCss('a[href="/cancellation/6"]')
38+
await link6.hover()
39+
40+
// Hover over a different link to increase its relative priority. This
41+
// one is near the top of the document, so its route tree is already
42+
// in-flight.
3443
const link2 = await browser.elementByCss('a[href="/cancellation/2"]')
3544
await link2.hover()
36-
37-
// Hover over a different link to increase its relative priority.
38-
const link5 = await browser.elementByCss('a[href="/cancellation/5"]')
39-
await link5.hover()
4045
},
4146
// Assert that the segment data is prefetched in the expected order.
4247
[
4348
// The last link we hovered over should be the first to prefetch.
44-
{ includes: 'Content of page 5' },
45-
// The second-to-last link we hovered over should come next.
4649
{ includes: 'Content of page 2' },
50+
// The second-to-last link we hovered over should come next, ahead of
51+
// the other default tasks.
52+
{ includes: 'Content of page 6' },
4753
// Then all the other links come after that. (We don't need to assert
4854
// on every single prefetch response. I picked one of them arbitrarily.)
4955
{ includes: 'Content of page 4' },
5056
]
5157
)
5258
})
5359

60+
it('prioritizes links nearest the top of the document when many enter the viewport at once', async () => {
61+
let act: ReturnType<typeof createRouterAct>
62+
const browser = await next.browser('/cancellation', {
63+
beforePageLoad(p: Playwright.Page) {
64+
act = createRouterAct(p)
65+
},
66+
})
67+
68+
const checkbox = await browser.elementByCss('input[type="checkbox"]')
69+
await act(
70+
async () => {
71+
// Reveal all the links at once. They all enter the viewport in the same
72+
// IntersectionObserver callback, which reports them in document order
73+
// (page 1 through 7).
74+
await checkbox.click()
75+
},
76+
// The prefetch scheduler gives the highest priority to the most recently
77+
// scheduled task. Rather than letting the link lowest in the document win
78+
// (which is what happens if we schedule the observer entries in the order
79+
// they're reported), we schedule them in reverse, so the link nearest the
80+
// top of the document is scheduled last and therefore prefetched first.
81+
[
82+
{ includes: 'Content of page 1' },
83+
{ includes: 'Content of page 2' },
84+
{ includes: 'Content of page 3' },
85+
]
86+
)
87+
})
88+
5489
// TODO: This test no longer works as-written because the metadata is now
5590
// fetched separately from the route tree. Need to rewrite to assert on
5691
// something that appears in the route tree and is relatively stable, like a
@@ -129,19 +164,25 @@ describe('segment cache prefetch scheduling', () => {
129164
// Hover over a link. This will initiate a request for the route tree,
130165
// but before we're able to fetch the segments, we'll have already
131166
// hovered over a different link.
132-
const link2 = await browser.elementByCss('a[href="/cancellation/2"]')
133-
await link2.hover()
167+
//
168+
// We hover over links near the bottom of the document (pages 6 and 7).
169+
// By default the scheduler prioritizes the links nearest the top, so
170+
// these links' route trees have *not* already been requested — which is
171+
// what lets us observe that hovering initiates a new request that
172+
// exceeds the default bandwidth limit.
173+
const link6 = await browser.elementByCss('a[href="/cancellation/6"]')
174+
await link6.hover()
134175

135176
// Immediately hover over a different link.
136-
const link3 = await browser.elementByCss('a[href="/cancellation/3"]')
137-
await link3.hover()
177+
const link7 = await browser.elementByCss('a[href="/cancellation/7"]')
178+
await link7.hover()
138179
}, [
139180
// The most recently hovered link is allowed to finish loading its
140181
// segment data.
141-
{ includes: 'Content of page 3' },
182+
{ includes: 'Content of page 7' },
142183
// The previously hovered link was downgraded to the default priority,
143184
// so it should still be blocked.
144-
{ includes: 'Content of page 2', block: 'reject' },
185+
{ includes: 'Content of page 6', block: 'reject' },
145186
])
146187
}, [
147188
// Assert that everything else proceeds in the expected order. We don't
@@ -151,7 +192,7 @@ describe('segment cache prefetch scheduling', () => {
151192
// The previously hovered link is the next to finish loading, because
152193
// even though it was downgraded to the default priority, it was still
153194
// moved ahead of the other default tasks.
154-
{ includes: 'Content of page 2' },
195+
{ includes: 'Content of page 6' },
155196
// Next are the links that were revealed by the "Show More" button.
156197
{ includes: 'Content of page 8' },
157198
// Then the rest.

0 commit comments

Comments
 (0)