rsnext/packages/next/client/on-demand-entries-utils.js
JJ Kasper 4c35b7e704
Add warning on stalled page load possibly from too many tabs open (#6514)
* Add warning on stalled page load possibly from too many tabs open

* Add test for stalled warning

* Update onDemand pinging to close on routeChangeStart and added
warning when onDemand handler detects multiple tabs from the same
browser
2019-03-02 16:51:14 -06:00

55 lines
1.4 KiB
JavaScript

/* global window, location */
import fetch from 'unfetch'
let evtSource
export let currentPage
let retryTimeout
const retryWait = 5000
export function closePing () {
if (evtSource) evtSource.close()
}
export function setupPing (assetPrefix, pathnameFn, retry) {
const pathname = pathnameFn()
// Make sure to only create new EventSource request if page has changed
if (pathname === currentPage && !retry) return
currentPage = pathname
// close current EventSource connection
closePing()
const url = `${assetPrefix}/_next/on-demand-entries-ping?page=${currentPage}`
evtSource = new window.EventSource(url)
evtSource.onerror = () => {
retryTimeout = setTimeout(
() => setupPing(assetPrefix, pathnameFn, true),
retryWait
)
}
evtSource.onopen = () => {
clearTimeout(retryTimeout)
}
evtSource.onmessage = event => {
try {
const payload = JSON.parse(event.data)
if (payload.invalid) {
// Payload can be invalid even if the page does not exist.
// So, we need to make sure it exists before reloading.
fetch(location.href, {
credentials: 'same-origin'
}).then(pageRes => {
if (pageRes.status === 200) {
location.reload()
}
})
}
} catch (err) {
console.error('on-demand-entries failed to parse response', err)
}
}
}