@@ -15,3 +15,56 @@ <h2>Dummy Content</h2>
1515 < p > "Sometimes you just need a blank canvas before the masterpiece arrives."</ p >
1616 </ blockquote >
1717</ section >
18+
19+ < section class ="dummy-page ">
20+ < h2 > WebAssembly Greeting Demo</ h2 >
21+ < p >
22+ The button below loads < code > wasm/hello.wasm</ code > —a module compiled from < code > hello.c</ code > —
23+ and calls the exported < code > get_greeting</ code > function to display its message.
24+ </ p >
25+ < button type ="button " id ="load-wasm "> Load greeting from WebAssembly</ button >
26+ < pre id ="wasm-result " aria-live ="polite "> Click the button to fetch the WebAssembly module.</ pre >
27+ </ section >
28+
29+ < script type ="module ">
30+ const wasmUrl = "{{ '/wasm/hello.wasm' | relative_url }}" ;
31+ const loadButton = document . getElementById ( 'load-wasm' ) ;
32+ const output = document . getElementById ( 'wasm-result' ) ;
33+
34+ async function loadGreetingFromWasm ( ) {
35+ output . textContent = 'Loading greeting...' ;
36+
37+ try {
38+ const response = await fetch ( wasmUrl ) ;
39+ if ( ! response . ok ) {
40+ throw new Error ( `Unexpected response: ${ response . status } ${ response . statusText } ` ) ;
41+ }
42+
43+ const buffer = await response . arrayBuffer ( ) ;
44+ const { instance } = await WebAssembly . instantiate ( buffer , { } ) ;
45+ const { exports } = instance ;
46+
47+ if ( typeof exports . get_greeting !== 'function' || typeof exports . get_greeting_length !== 'function' ) {
48+ throw new Error ( 'Expected WebAssembly exports were not found.' ) ;
49+ }
50+
51+ const pointer = exports . get_greeting ( ) ;
52+ const length = exports . get_greeting_length ( ) ;
53+ const memory = exports . memory ;
54+
55+ if ( ! ( memory instanceof WebAssembly . Memory ) ) {
56+ throw new Error ( 'WebAssembly memory export is missing.' ) ;
57+ }
58+
59+ const bytes = new Uint8Array ( memory . buffer , pointer , length ) ;
60+ const greeting = new TextDecoder ( 'utf-8' ) . decode ( bytes ) ;
61+
62+ output . textContent = greeting ;
63+ } catch ( error ) {
64+ console . error ( 'Failed to load WebAssembly module:' , error ) ;
65+ output . textContent = `Failed to load greeting: ${ error . message } ` ;
66+ }
67+ }
68+
69+ loadButton . addEventListener ( 'click' , loadGreetingFromWasm ) ;
70+ </ script >
0 commit comments