-
Notifications
You must be signed in to change notification settings - Fork 1
/
__modules__.ts
71 lines (65 loc) · 2.46 KB
/
__modules__.ts
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
export function loadModules(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 = () => {
doneCallback();
};
tag.onerror = () => {
throw new Error('failed to load ' + url);
};
tag.async = true;
tag.src = urlPrefix + url;
document.head.appendChild(tag);
}
// load and initialize a wasm module
function loadWasmModuleAsync(moduleName, jsUrl, binaryUrl, doneCallback) {
loadScriptAsync(jsUrl, function () {
window[moduleName + 'Lib'] = window[moduleName];
(window[moduleName] as any)({ locateFile: () => urlPrefix + binaryUrl }).then( function () {
doneCallback();
});
});
}
// load and initialize an asm.js module
function loadAsmModuleAsync(moduleName, jsUrl, doneCallback) {
return loadScriptAsync(jsUrl, function () {
window[moduleName] = (window[moduleName] as any)();
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 (wasm) {
loadWasmModuleAsync(m.moduleName, m.glueUrl, m.wasmUrl, asyncCallback);
} else {
if (!m.fallbackUrl) {
throw new Error('wasm not supported and no fallback supplied for module ' + m.moduleName);
}
loadAsmModuleAsync(m.moduleName, m.fallbackUrl, asyncCallback);
}
});
}
};