-
-
Notifications
You must be signed in to change notification settings - Fork 381
/
loadableReady.js
76 lines (66 loc) · 1.95 KB
/
loadableReady.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/* eslint-disable no-underscore-dangle, camelcase */
/* eslint-env browser */
import { warn } from './util'
import { getRequiredChunkKey } from './sharedInternals'
import { LOADABLE_SHARED } from './shared'
const BROWSER = typeof window !== 'undefined'
export default function loadableReady(
done = () => {},
{ namespace = '' } = {},
) {
if (!BROWSER) {
warn('`loadableReady()` must be called in browser only')
done()
return Promise.resolve()
}
let requiredChunks = null
if (BROWSER) {
const id = getRequiredChunkKey(namespace)
const dataElement = document.getElementById(id)
if (dataElement) {
requiredChunks = JSON.parse(dataElement.textContent)
const extElement = document.getElementById(`${id}_ext`)
if (extElement) {
const { namedChunks } = JSON.parse(extElement.textContent)
namedChunks.forEach(chunkName => {
LOADABLE_SHARED.initialChunks[chunkName] = true
})
} else {
// version mismatch
throw new Error(
'loadable-component: @loadable/server does not match @loadable/component',
)
}
}
}
if (!requiredChunks) {
warn(
'`loadableReady()` requires state, please use `getScriptTags` or `getScriptElements` server-side',
)
done()
return Promise.resolve()
}
let resolved = false
return new Promise(resolve => {
window.__LOADABLE_LOADED_CHUNKS__ = window.__LOADABLE_LOADED_CHUNKS__ || []
const loadedChunks = window.__LOADABLE_LOADED_CHUNKS__
const originalPush = loadedChunks.push.bind(loadedChunks)
function checkReadyState() {
if (
requiredChunks.every(chunk =>
loadedChunks.some(([chunks]) => chunks.indexOf(chunk) > -1),
)
) {
if (!resolved) {
resolved = true
resolve()
}
}
}
loadedChunks.push = (...args) => {
originalPush(...args)
checkReadyState()
}
checkReadyState()
}).then(done)
}