Wusevar i Wusevar i - 1 year ago 160
C Question

emscripten window.onload equivalent

I have a single html file where I copy paste the emscripten generated code into it's


The browsers run the emscripten code before all the html file has been processed

So if the emscripten code uses an html element that is after the
region, it won't work

here it says that the C main() function is called after the page is fully loaded but that is wrong

How can I make the C code run after the html file is fully loaded?

Answer Source

This page is a tutorial-style guide to using Emscripten to compile to JavaScript and including that JavaScript in your own page. It includes not running the C program until a button is clicked on the HTML document.

In short, normally, rather than copy and pasting Emscripten generated code, it is easier to load the Emscripten JavaScript in a separate request, for example, in your main document by running the JavaScript:

      var script = document.createElement('script');
      script.src = "my_emscripten_script.js";

In Emscripten you don't need to have a main function at all, that tutorial I link to renames the main function mainf, if you export it by passing the command line flag

      -s EXPORTED_FUNCTIONS='["_mainf"]'

to emcc at compile time (note the leading underscore!) and then you can call it from JavaScript when you want to start your C program. How you call an exported function from JavaScript is described here, but for the renamed mainf function will be a JavaScript call like this:

Module.ccall('mainf', null, null);

If you want to make sure that that isn't called until the Emscripten run-time is ready, the Module object that Emscripten uses can have a onRuntimeInitialized method added to it. This function is called when Emscripten is ready, so you can use this for doing your call to ccall to start the program.

Having said all this, I am surprised that your main function is being run before the document is ready. Please be aware that some of the emscripten functions in html5.h (such as the functions for requesting the canvas goes full-screen) are only functional upon user initiated events (for security reasons), so it could be that that is your problem rather than at what point during page load main is called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download