-
Notifications
You must be signed in to change notification settings - Fork 0
/
__modules__.js
70 lines (65 loc) · 2.5 KB
/
__modules__.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
var loadModules = function (modules, urlPrefix, doneCallback) {
// check for wasm module support
function wasmSupported() {
try {
if (typeof WebAssembly === "object" && typeof WebAssembly.instantiate === "function") {
const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00));
if (module instanceof WebAssembly.Module)
return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
}
} catch (e) { }
return false;
}
// load a script
function loadScriptAsync(url, doneCallback) {
var tag = document.createElement('script');
tag.onload = function () {
doneCallback();
};
tag.onerror = function () {
throw new Error('failed to load ' + url);
};
tag.async = true;
tag.src = url;
tag.crossOrigin = 'anonymous';
document.head.appendChild(tag);
}
// load and initialize a wasm module
function loadWasmModuleAsync(moduleName, jsUrl, binaryUrl, doneCallback) {
loadScriptAsync(jsUrl, function () {
var lib = window[moduleName];
window[moduleName + 'Lib'] = lib;
lib({ locateFile: function () { return binaryUrl; } } ).then( function (instance) {
window[moduleName] = instance;
doneCallback();
});
});
}
if (typeof modules === "undefined" || modules.length === 0) {
// caller may depend on callback behaviour being async
setTimeout(doneCallback);
} else {
var asyncCounter = modules.length;
var asyncCallback = function () {
asyncCounter--;
if (asyncCounter === 0) {
doneCallback();
}
};
var wasm = wasmSupported();
modules.forEach(function (m) {
if (!m.hasOwnProperty('preload') || m.preload) {
if (wasm) {
loadWasmModuleAsync(m.moduleName, urlPrefix + m.glueUrl, urlPrefix + m.wasmUrl, asyncCallback);
} else {
if (!m.fallbackUrl) {
throw new Error('wasm not supported and no fallback supplied for module ' + m.moduleName);
}
loadWasmModuleAsync(m.moduleName, urlPrefix + m.fallbackUrl, "", asyncCallback);
}
} else {
asyncCallback();
}
});
}
};