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

Fix #11107 - don't prefetch preloaded modules #22818

Merged
merged 9 commits into from
Sep 19, 2021
6 changes: 5 additions & 1 deletion packages/next/client/route-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ function prefetchViaDom(
link?: HTMLLinkElement
): Promise<any> {
return new Promise<void>((res, rej) => {
if (document.querySelector(`link[rel="prefetch"][href^="${href}"]`)) {
const selector = `
link[rel="prefetch"][href^="${href}"],
link[rel="preload"][href^="${href}"],
script[src^="${href}"]`
if (document.querySelector(selector)) {
return res()
}

Expand Down
23 changes: 23 additions & 0 deletions test/integration/preload-viewport/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,29 @@ describe('Prefetching Links in viewport', () => {
expect(found).toBe(false)
})

it('should not prefetch already loaded scripts', async () => {
const browser = await webdriver(appPort, '/')

const scriptSrcs = await browser.eval(`(function() {
return Array.from(document.querySelectorAll('script'))
.map(function(el) {
return el.src && new URL(el.src).pathname
}).filter(Boolean)
})()`)

await browser.eval('next.router.prefetch("/")')

const linkHrefs = await browser.eval(`(function() {
return Array.from(document.querySelectorAll('link'))
.map(function(el) {
return el.href && new URL(el.href).pathname
}).filter(Boolean)
})()`)

console.log({ linkHrefs, scriptSrcs })
expect(linkHrefs.some((href) => scriptSrcs.includes(href))).toBe(false)
})

it('should not duplicate prefetches', async () => {
const browser = await webdriver(appPort, '/multi-prefetch')

Expand Down