-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbrowser.js
104 lines (89 loc) · 2.42 KB
/
browser.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Store dynamic bundle exports.
var cache = {}
// Store dynamic bundle loading callbacks, in case the same module is imported
// multiple times simultaneously.
var receivers = {}
function noop () {}
// Attach a promise to a callback, that is settled when the callback is called.
function promisify (cb) {
var res = noop
var rej = noop
var promise = typeof Promise !== 'undefined' && new Promise(function (resolve, reject) {
res = resolve
rej = reject
})
promisifiedCb.p = promise
return promisifiedCb
function promisifiedCb (err, val) {
if (err) rej(err)
else res(val)
if (cb) cb(err, val)
}
}
function load (index, cb) {
cb = promisify(cb)
// We already have this bundle.
if (cache[index]) {
setTimeout(cb.bind(null, null, cache[index]), 0)
return cb.p
}
var url = load.b[index]
// TODO throw an error if we don't have the url
// Combine callbacks if another one was already registered.
var prev = receivers[index]
receivers[index] = onload
function onload (err, result) {
if (prev) prev(err, result)
else if (!err) cache[index] = result
if (cb) cb(err, result)
delete receivers[index]
}
// The <script> element for this bundle was already added.
if (prev) return cb.p
var integrity = load.s[index]
var crossOrigin = load.c
var s = document.createElement('script')
s.async = true
if (crossOrigin) s.crossOrigin = crossOrigin
if (integrity) s.integrity = integrity
s.type = 'application/javascript'
s.src = url
s.onerror = function () {
onload(Error('Failed to load'))
}
document.body.appendChild(s)
return cb.p
}
// Called by dynamic bundles once they have loaded.
function loadedBundle (index, result) {
if (receivers[index]) {
receivers[index](null, result)
} else {
cache[index] = result
}
}
// "Load" a module that we know is included in this bundle.
var nextTick = window.setImmediate || window.setTimeout
function loadLocal (requirer, onload) {
onload = promisify(onload)
nextTick(function () {
// Just execute the module if no callback is provided
if (!onload) return requirer()
try {
onload(null, requirer())
} catch (err) {
onload(err)
}
})
return onload.p
}
// Map dynamic bundle entry point IDs to URLs.
load.b = {}
// Subresource integrity hashes
load.s = {}
// Cross-origin loading
load.c = null
// Used by the bundle.
load.l = loadedBundle
load.t = loadLocal
module.exports = load