Unverified Commit 41e24a51 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Speculate Navigations for Client-Side JS (#10560)

* Speculate Navigations for Client-Side JS

* add tests

* avoid desctructure
parent 9cfc09e3
declare const __NEXT_DATA__: any declare const __NEXT_DATA__: any
import { resolve, parse, UrlObject } from 'url' import React, { Children, Component } from 'react'
import React, { Component, Children } from 'react' import { parse, resolve, UrlObject } from 'url'
import Router from './router' import { PrefetchOptions } from '../next-server/lib/router/router'
import { import {
execOnce, execOnce,
formatWithValidation, formatWithValidation,
getLocationOrigin, getLocationOrigin,
} from '../next-server/lib/utils' } from '../next-server/lib/utils'
import Router from './router'
function isLocal(href: string) { function isLocal(href: string) {
const url = parse(href, false, true) const url = parse(href, false, true)
...@@ -127,14 +128,18 @@ class Link extends Component<LinkProps> { ...@@ -127,14 +128,18 @@ class Link extends Component<LinkProps> {
this.cleanUpListeners() this.cleanUpListeners()
} }
getHref() { getPaths() {
const { pathname } = window.location const { pathname } = window.location
const { href: parsedHref } = this.formatUrls(this.props.href, this.props.as) const { href: parsedHref, as: parsedAs } = this.formatUrls(
return resolve(pathname, parsedHref) this.props.href,
this.props.as
)
const resolvedHref = resolve(pathname, parsedHref)
return [resolvedHref, parsedAs ? resolve(pathname, parsedAs) : resolvedHref]
} }
handleRef(ref: Element) { handleRef(ref: Element) {
const isPrefetched = prefetched[this.getHref()] const isPrefetched = prefetched[this.getPaths()[0]]
if (this.p && IntersectionObserver && ref && ref.tagName) { if (this.p && IntersectionObserver && ref && ref.tagName) {
this.cleanUpListeners() this.cleanUpListeners()
...@@ -201,11 +206,11 @@ class Link extends Component<LinkProps> { ...@@ -201,11 +206,11 @@ class Link extends Component<LinkProps> {
}) })
} }
prefetch() { prefetch(options?: PrefetchOptions) {
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 href = this.getHref() const [href, asPath] = this.getPaths()
Router.prefetch(href) Router.prefetch(href, asPath, options)
prefetched[href] = true prefetched[href] = true
} }
...@@ -239,7 +244,7 @@ class Link extends Component<LinkProps> { ...@@ -239,7 +244,7 @@ class Link extends Component<LinkProps> {
if (child.props && typeof child.props.onMouseEnter === 'function') { if (child.props && typeof child.props.onMouseEnter === 'function') {
child.props.onMouseEnter(e) child.props.onMouseEnter(e)
} }
this.prefetch() this.prefetch({ priority: true })
}, },
onClick: (e: React.MouseEvent) => { onClick: (e: React.MouseEvent) => {
if (child.props && typeof child.props.onClick === 'function') { if (child.props && typeof child.props.onClick === 'function') {
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
import { ParsedUrlQuery } from 'querystring' import { ParsedUrlQuery } from 'querystring'
import { ComponentType } from 'react' import { ComponentType } from 'react'
import { parse, UrlObject } from 'url' import { parse, UrlObject } from 'url'
import mitt, { MittEmitter } from '../mitt' import mitt, { MittEmitter } from '../mitt'
import { import {
AppContextType, AppContextType,
...@@ -52,6 +51,10 @@ export type NextRouter = BaseRouter & ...@@ -52,6 +51,10 @@ export type NextRouter = BaseRouter &
| 'isFallback' | 'isFallback'
> >
export type PrefetchOptions = {
priority?: boolean
}
type RouteInfo = { type RouteInfo = {
Component: ComponentType Component: ComponentType
props?: any props?: any
...@@ -652,11 +655,16 @@ export default class Router implements BaseRouter { ...@@ -652,11 +655,16 @@ export default class Router implements BaseRouter {
} }
/** /**
* Prefetch `page` code, you may wait for the data during `page` rendering. * Prefetch page code, you may wait for the data during page rendering.
* This feature only works in production! * This feature only works in production!
* @param url of prefetched `page` * @param url the href of prefetched page
* @param asPath the as path of the prefetched page
*/ */
prefetch(url: string): Promise<void> { prefetch(
url: string,
asPath: string = url,
options: PrefetchOptions = {}
): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const { pathname, protocol } = parse(url) const { pathname, protocol } = parse(url)
...@@ -674,8 +682,9 @@ export default class Router implements BaseRouter { ...@@ -674,8 +682,9 @@ export default class Router implements BaseRouter {
return return
} }
const route = toRoute(pathname) this.pageLoader[options.priority ? 'loadPage' : 'prefetch'](
this.pageLoader.prefetch(route).then(resolve, reject) toRoute(pathname)
).then(() => resolve(), reject)
}) })
} }
......
...@@ -22,7 +22,7 @@ export default () => { ...@@ -22,7 +22,7 @@ export default () => {
/> />
<p id="scroll-to-me">Hi 👋</p> <p id="scroll-to-me">Hi 👋</p>
<Link href="/another"> <Link href="/another">
<a>to /another</a> <a id="link-another">to /another</a>
</Link> </Link>
</div> </div>
) )
......
/* eslint-env jest */ /* eslint-env jest */
/* global jasmine */ /* global jasmine */
import webdriver from 'next-webdriver'
import { join } from 'path'
import { import {
nextServer, nextServer,
runNextCommand, runNextCommand,
...@@ -9,6 +7,8 @@ import { ...@@ -9,6 +7,8 @@ import {
stopApp, stopApp,
waitFor, waitFor,
} from 'next-test-utils' } from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
...@@ -98,24 +98,66 @@ describe('Prefetching Links in viewport', () => { ...@@ -98,24 +98,66 @@ describe('Prefetching Links in viewport', () => {
} }
}) })
it('should fallback to prefetching onMouseEnter with invalid ref', async () => { it('should prefetch with link in viewport and inject script on hover', async () => {
let browser let browser
try { try {
browser = await webdriver(appPort, '/invalid-ref') browser = await webdriver(appPort, '/')
await browser.elementByCss('#btn-link').moveTo() await browser.elementByCss('#scroll-to-another').click()
await waitFor(2 * 1000) await waitFor(2 * 1000)
const links = await browser.elementsByCss('link[rel=prefetch]') const links = await browser.elementsByCss('link[rel=prefetch]')
let found = false let foundLink = false
for (const link of links) { for (const link of links) {
const href = await link.getAttribute('href') const href = await link.getAttribute('href')
if (href.includes('another')) { if (href.includes('another')) {
found = true foundLink = true
break break
} }
} }
expect(found).toBe(true) expect(foundLink).toBe(true)
await browser.elementByCss('#link-another').moveTo()
await waitFor(2 * 1000)
const scripts = await browser.elementsByCss(
// Mouse hover is a high-priority fetch
'script:not([async])'
)
let scriptFound = false
for (const aScript of scripts) {
const href = await aScript.getAttribute('src')
if (href.includes('another')) {
scriptFound = true
break
}
}
expect(scriptFound).toBe(true)
} finally {
if (browser) await browser.close()
}
})
it('should inject a <script> tag when onMouseEnter (even with invalid ref)', async () => {
let browser
try {
browser = await webdriver(appPort, '/invalid-ref')
await browser.elementByCss('#btn-link').moveTo()
await waitFor(2 * 1000)
const scripts = await browser.elementsByCss(
// Mouse hover is a high-priority fetch
'script:not([async])'
)
let scriptFound = false
for (const aScript of scripts) {
const href = await aScript.getAttribute('src')
if (href.includes('another')) {
scriptFound = true
break
}
}
expect(scriptFound).toBe(true)
} finally { } finally {
if (browser) await browser.close() if (browser) await browser.close()
} }
......
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