|
7 | 7 | const output = document.getElementById('wasm-result'); |
8 | 8 | const utf8 = new TextDecoder(); |
9 | 9 |
|
10 | | -async function instantiateWasm(url, imports = {}) { |
11 | | - const res = await fetch(url); |
12 | | - return await WebAssembly.instantiateStreaming(res, imports); |
13 | | -} |
14 | | - |
15 | 10 | async function loadGreetingFromWasm() { |
16 | | - if (output) output.textContent = 'Loading greeting...'; |
17 | | - |
18 | | - try { |
19 | | - const { instance } = await instantiateWasm(new URL(wasmPath, document.baseURI)); |
20 | | - const { exports } = instance; |
21 | | - |
22 | | - const getGreeting = exports.get_greeting || exports._get_greeting; |
23 | | - const getGreetingLength = exports.get_greeting_length || exports._get_greeting_length; |
24 | | - |
25 | | - if (typeof getGreeting !== 'function' || typeof getGreetingLength !== 'function') { |
26 | | - throw new Error('Expected WebAssembly exports "get_greeting" and "get_greeting_length" not found.'); |
27 | | - } |
28 | | - |
29 | | - // Some toolchains expose an optional initializer (not needed here, but harmless) |
30 | | - if (typeof exports._initialize === 'function') { |
31 | | - exports._initialize(); |
32 | | - } |
33 | | - |
34 | | - const memory = exports.memory; |
35 | | - if (!(memory instanceof WebAssembly.Memory)) { |
36 | | - throw new Error('WebAssembly memory export is missing.'); |
37 | | - } |
38 | | - |
39 | | - const ptr = getGreeting(); |
40 | | - const len = getGreetingLength(); |
| 11 | + output.textContent = 'Loading greeting...'; |
41 | 12 |
|
42 | | - const bytes = new Uint8Array(memory.buffer, ptr, len); |
43 | | - const greeting = utf8.decode(bytes); |
| 13 | + const res = await fetch(new URL(wasmPath, document.baseURI)); |
| 14 | + const { instance: { exports } } = await WebAssembly.instantiateStreaming(res, {}); |
| 15 | + if (typeof exports._initialize === 'function') exports._initialize(); |
| 16 | + |
| 17 | + const ptr = exports.get_greeting(); |
| 18 | + const len = exports.get_greeting_length(); |
| 19 | + const bytes = new Uint8Array(exports.memory.buffer, ptr, len); |
44 | 20 |
|
45 | | - if (output) output.textContent = greeting; |
46 | | - } catch (error) { |
47 | | - console.error(error); |
48 | | - if (output) output.textContent = `Failed to load greeting: ${error.message}`; |
49 | | - } |
| 21 | + output.textContent = utf8.decode(bytes); |
50 | 22 | } |
51 | 23 |
|
52 | 24 | loadButton?.addEventListener('click', loadGreetingFromWasm); |
|
0 commit comments