Unverified Commit 1ec7716f authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Prevent re-observing for an already prefetched page (#9644)

* Prevent re-observing for an already prefetched page

* Update size-limit test

* Move prefetched setting

* Remove extra prefetched setting
parent fd1636ae
...@@ -110,6 +110,7 @@ const listenToIntersections = (el: any, cb: any) => { ...@@ -110,6 +110,7 @@ const listenToIntersections = (el: any, cb: any) => {
class Link extends Component<LinkProps> { class Link extends Component<LinkProps> {
static propTypes?: any static propTypes?: any
p: boolean p: boolean
constructor(props: LinkProps) { constructor(props: LinkProps) {
super(props) super(props)
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
...@@ -128,12 +129,25 @@ class Link extends Component<LinkProps> { ...@@ -128,12 +129,25 @@ class Link extends Component<LinkProps> {
this.cleanUpListeners() this.cleanUpListeners()
} }
getHref() {
const { pathname } = window.location
const { href: parsedHref } = this.formatUrls(this.props.href, this.props.as)
return resolve(pathname, parsedHref)
}
handleRef(ref: Element) { handleRef(ref: Element) {
const isPrefetched = (Router.router as any).pageLoader.prefetched[
this.getHref()
]
if (this.p && IntersectionObserver && ref && ref.tagName) { if (this.p && IntersectionObserver && ref && ref.tagName) {
this.cleanUpListeners() this.cleanUpListeners()
this.cleanUpListeners = listenToIntersections(ref, () => {
this.prefetch() if (!isPrefetched) {
}) this.cleanUpListeners = listenToIntersections(ref, () => {
this.prefetch()
})
}
} }
} }
...@@ -194,12 +208,8 @@ class Link extends Component<LinkProps> { ...@@ -194,12 +208,8 @@ class Link extends Component<LinkProps> {
prefetch() { prefetch() {
if (!this.p || typeof window === 'undefined') return if (!this.p || typeof window === 'undefined') return
// Prefetch the JSON page if asked (only in the client) // Prefetch the JSON page if asked (only in the client)
const { pathname } = window.location Router.prefetch(this.getHref())
const { href: parsedHref } = this.formatUrls(this.props.href, this.props.as)
const href = resolve(pathname, parsedHref)
Router.prefetch(href)
} }
render() { render() {
......
...@@ -38,6 +38,7 @@ export default class PageLoader { ...@@ -38,6 +38,7 @@ export default class PageLoader {
this.assetPrefix = assetPrefix this.assetPrefix = assetPrefix
this.pageCache = {} this.pageCache = {}
this.prefetched = {}
this.pageRegisterEvents = mitt() this.pageRegisterEvents = mitt()
this.loadingRoutes = {} this.loadingRoutes = {}
if (process.env.__NEXT_GRANULAR_CHUNKS) { if (process.env.__NEXT_GRANULAR_CHUNKS) {
...@@ -220,12 +221,14 @@ export default class PageLoader { ...@@ -220,12 +221,14 @@ export default class PageLoader {
// n.b. If preload is not supported, we fall back to `loadPage` which has // n.b. If preload is not supported, we fall back to `loadPage` which has
// its own deduping mechanism. // its own deduping mechanism.
if ( if (
this.prefetched[route] ||
document.querySelector( document.querySelector(
`link[rel="${prefetchOrPreload}"][href^="${url}"], script[data-next-page="${route}"]` `link[rel="${prefetchOrPreload}"][href^="${url}"], script[data-next-page="${route}"]`
) )
) { ) {
return return
} }
this.prefetched[route] = true
// Inspired by quicklink, license: https://github.com/GoogleChromeLabs/quicklink/blob/master/LICENSE // Inspired by quicklink, license: https://github.com/GoogleChromeLabs/quicklink/blob/master/LICENSE
let cn let cn
...@@ -251,7 +254,7 @@ export default class PageLoader { ...@@ -251,7 +254,7 @@ export default class PageLoader {
} }
if (isDependency) { if (isDependency) {
// loadPage will automatically handle depencies, so no need to // loadPage will automatically handle dependencies, so no need to
// preload them manually // preload them manually
return return
} }
......
...@@ -588,10 +588,15 @@ export default class Router implements BaseRouter { ...@@ -588,10 +588,15 @@ export default class Router implements BaseRouter {
} }
return return
} }
// Prefetch is not supported in development mode because it would trigger on-demand-entries
if (process.env.NODE_ENV !== 'production') return
// @ts-ignore pathname is always defined // @ts-ignore pathname is always defined
const route = toRoute(pathname) const route = toRoute(pathname)
// Prefetch is not supported in development mode because it would trigger on-demand-entries
if (process.env.NODE_ENV !== 'production') {
// mark it as prefetched for debugging in dev
this.pageLoader.prefetched[route] = true
return
}
this.pageLoader.prefetch(route).then(resolve, reject) this.pageLoader.prefetch(route).then(resolve, reject)
}) })
} }
......
import Link from 'next/link'
export default () => {
return (
<p>
<Link href="/first">
<a>to /first</a>
</Link>
</p>
)
}
...@@ -158,4 +158,19 @@ describe('Prefetching Links in viewport', () => { ...@@ -158,4 +158,19 @@ describe('Prefetching Links in viewport', () => {
// Verify encoding // Verify encoding
expect(hrefs.some(e => e.includes(`%5Bhello%5D.js`))).toBe(true) expect(hrefs.some(e => e.includes(`%5Bhello%5D.js`))).toBe(true)
}) })
it('should not add an another observer for a prefetched page', async () => {
const browser = await webdriver(appPort, '/')
await waitFor(2 * 1000)
await browser.eval(`(function() {
window.calledPrefetch = false
window.next.router.prefetch = function() {
window.calledPrefetch = true
}
window.next.router.push('/de-duped')
})()`)
await waitFor(2 * 1000)
const calledPrefetch = await browser.eval(`window.calledPrefetch`)
expect(calledPrefetch).toBe(false)
})
}) })
...@@ -81,7 +81,7 @@ describe('Production response size', () => { ...@@ -81,7 +81,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizeKilobytes - 229 const delta = responseSizeKilobytes - 230
expect(delta).toBeLessThanOrEqual(0) // don't increase size expect(delta).toBeLessThanOrEqual(0) // don't increase size
expect(delta).toBeGreaterThanOrEqual(-1) // don't decrease size without updating target expect(delta).toBeGreaterThanOrEqual(-1) // don't decrease size without updating target
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment