RequireJS loads the data-main script asynchronously. Thus there is a race condition between the page loading and main.js loading. If main.js finishes loading first, window.onload
will be set and you will see "render ran". If the page finishes loading first, you won't. Which of these two outcomes occurs is indeterminate in general, but since the example page you've given is extremely short, it will usually finish loading before main.js has been fetched from the server.
If you want your module to run after the page loads, you can add a dependency on the domReady module:
<script src="require.js"></script> <!-- note, no 'data-main' -->
<script>require( ['main'], function() {} );</script>
main.js:
define(['domReady!'], function() {
// ...
});
This is probably an issue with RequireJS and the fact that the page is already loaded. RequireJS should already be waiting for all the files to load so use the below code.
Example:
console.log("main.js ran");
function render() {
console.log("render ran");
}
render();
If you are trying to wait for an HTML element to load use jQuery:
//will run once the page DOM is ready
$(element).ready(function(){
...
});
//will run once the entire page is
//loaded including images and iframes
$(element).load(function(){
...
});