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

Get rid of mitt.

This commit is contained in:
Arunoda Susiripala 2017-04-11 15:35:29 +05:30
parent c077ebe7ba
commit fb2f90bec1

View file

@ -1,6 +1,4 @@
/* global window, document */ /* global window, document */
import mitt from 'mitt'
const webpackModule = module const webpackModule = module
export default class PageLoader { export default class PageLoader {
@ -8,7 +6,6 @@ export default class PageLoader {
this.buildId = buildId this.buildId = buildId
this.pageCache = {} this.pageCache = {}
this.pageLoadedHandlers = {} this.pageLoadedHandlers = {}
this.registerEvents = mitt()
this.loadingRoutes = {} this.loadingRoutes = {}
} }
@ -32,37 +29,41 @@ export default class PageLoader {
}) })
} }
return new Promise((resolve, reject) => { if (this.loadingRoutes[route]) {
const fire = ({ error, page }) => { return this.loadingRoutes[route]
this.registerEvents.off(route, fire)
if (error) {
reject(error)
} else {
resolve(page)
}
} }
this.registerEvents.on(route, fire) const loadingPromise = new Promise((resolve, reject) => {
this.loadScript(route, (error) => {
delete this.loadingRoutes[route]
// Load the script if not asked to load yet. if (error) return reject(error)
if (!this.loadingRoutes[route]) {
this.loadScript(route) const cachedPage = this.pageCache[route]
this.loadingRoutes[route] = true if (cachedPage.error) return reject(cachedPage.error)
} return resolve(cachedPage.page)
}) })
})
this.loadingRoutes[route] = loadingPromise
return loadingPromise
} }
loadScript (route) { loadScript (route, fn) {
route = this.normalizeRoute(route) route = this.normalizeRoute(route)
const script = document.createElement('script') const script = document.createElement('script')
const url = `/_next/${encodeURIComponent(this.buildId)}/page${route}` const url = `/_next/${encodeURIComponent(this.buildId)}/page${route}`
script.src = url script.src = url
script.type = 'text/javascript' script.type = 'text/javascript'
script.onerror = () => {
const error = new Error(`Error when loading route: ${route}`) script.onerror = (e) => {
this.registerEvents.emit(route, { error }) const error = new Error(`Network error occurred when loading route: ${route}`)
fn(error)
}
script.onload = () => {
fn()
} }
document.body.appendChild(script) document.body.appendChild(script)
@ -76,7 +77,6 @@ export default class PageLoader {
// add the page to the cache // add the page to the cache
this.pageCache[route] = { error, page } this.pageCache[route] = { error, page }
this.registerEvents.emit(route, { error, page })
}) })
} }