1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Reset prefetchCache when reloading a route. (#617)

* Reset prefetchCache when reloading a route.

* Prefetch again when there's a HMR reload.

* Make .send() to return a promise.
This commit is contained in:
Arunoda Susiripala 2017-01-02 03:18:14 -08:00 committed by Naoyuki Kanezawa
parent 856978918e
commit 01a17738db
2 changed files with 35 additions and 14 deletions

View file

@ -24,14 +24,21 @@ class Messenger {
this._resetCache()
}
send (payload, cb) {
if (this.serviceWorkerState === 'REGISTERED') {
this._send(payload, cb)
} else {
this.serviceWorkerReadyCallbacks.push(() => {
this._send(payload, cb)
})
}
send (payload) {
return new Promise((resolve, reject) => {
if (this.serviceWorkerState === 'REGISTERED') {
this._send(payload, handleCallback)
} else {
this.serviceWorkerReadyCallbacks.push(() => {
this._send(payload, handleCallback)
})
}
function handleCallback (err) {
if (err) return reject(err)
return resolve()
}
})
}
_send (payload, cb = () => {}) {
@ -99,23 +106,35 @@ if (hasServiceWorkerSupport()) {
messenger = new Messenger()
}
export function prefetch (href) {
function getPrefetchUrl (href) {
let { pathname } = urlParse(href)
const url = `/_next/pages${pathname}`
return url
}
export async function prefetch (href) {
if (!hasServiceWorkerSupport()) return
if (!isLocal(href)) return
// Register the service worker if it's not.
messenger.ensureInitialized()
let { pathname } = urlParse(href)
// Add support for the index page
const url = `/_next/pages${pathname}`
const url = getPrefetchUrl(href)
if (PREFETCHED_URLS[url]) return
messenger.send({ action: 'ADD_URL', url: url })
await messenger.send({ action: 'ADD_URL', url: url })
PREFETCHED_URLS[url] = true
}
export async function reloadIfPrefetched (href) {
const url = getPrefetchUrl(href)
if (!PREFETCHED_URLS[url]) return
delete PREFETCHED_URLS[url]
await prefetch(href)
}
export default class LinkPrefetch extends React.Component {
render () {
const { href } = this.props

View file

@ -2,6 +2,7 @@ import { parse, format } from 'url'
import evalScript from '../eval-script'
import shallowEquals from '../shallow-equals'
import { EventEmitter } from 'events'
import { reloadIfPrefetched } from '../prefetch'
export default class Router extends EventEmitter {
constructor (pathname, query, { Component, ErrorComponent, ctx } = {}) {
@ -77,6 +78,7 @@ export default class Router extends EventEmitter {
async reload (route) {
delete this.components[route]
await reloadIfPrefetched(route)
if (route !== this.route) return