Skip to content

Instantly share code, notes, and snippets.

@cnlohr
Last active November 13, 2020 16:22
Show Gist options
  • Save cnlohr/1979b6d1b52d3724ef64d6e706420b8a to your computer and use it in GitHub Desktop.
Save cnlohr/1979b6d1b52d3724ef64d6e706420b8a to your computer and use it in GitHub Desktop.
Issue with rendering order in HTML

//from https://stackoverflow.com/questions/64722413/force-webpage-dom-wait-on-promise

	initPage();

	async function initPage() {
		console.log('initializing page...');
		const wasmExports = await initWasm();
		renderPageContent(wasmExports);
	}

	// returns Promise<WasmModuleExports>
	async function initWasm() {
		const { instance } = await WebAssembly.instantiate(array, imports);
		return instance;
	}

	function renderPageContent(lwasmExports) {
		//Render a green square (we don't actually see this)
		wgl.clearColor( 0.,1.,0.,1. ); 
		wgl.clear( wgl.COLOR_BUFFER_BIT | wgl.COLOR_DEPTH_BIT );

		instance = lwasmExports;
		wasmExports = instance.exports;
		instance.exports.main();
		console.log('✓ page content rendered');
	}

	//This code executes BEFORE "✓ page content rendered"
	console.log( "should happen after initPage()" );

	//Render a red box.
	wgl.clearColor( 1.,0.,0.,1. ); 
	wgl.clear( wgl.COLOR_BUFFER_BIT | wgl.COLOR_DEPTH_BIT );
	console.log( "rendering red complete\n" );
	//After this function completes, the HTML document is rendered with the red box.

Outputs:

index.htlm:495 initializing page...
index.html:518 should happen after initPage()
index.html:523 rendering red complete
index.html:477 Main started.  This will appear in your browser console.
index.html:514 ✓ page content rendered
@cnlohr
Copy link
Author

cnlohr commented Nov 7, 2020

This code executes BEFORE "✓ page content rendered"

That's by design, you're adding code on the global scope, which runs within the main event loop. Once you put everything inside renderPageContent() you'll be golden. Asynchronous functions will always execute after synchronous code. MDN Event Loop article may be helpful in explaining that better than I.

When I do this, the page still renders a blank frame before the proper frame is rendered. The red square code is purely illustrational. It was just to demonstrate that code continues and the DOM is rendered before renderPageContent is executed. Is there some way to force events to be processed now this frame before going back?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment