Window.onload not calling function

With this index.html:

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
        <script data-main="main" src="require.js"></script>
    </head>
    <body>
        <p>This is the body</p>
        <canvas id="canvas1"></canvas>
    </body>
</html>

      

and this main.js

console.log("main.js ran");

function render() {
    console.log("render ran");
}

window.onload = render;

      

I expect the console output to be displayed:

main.js ran
render ran

      

"main.js ran" shows as expected, but "render ran" is not logged. The render function is never called. Why not?

+4


source to share


2 answers


RequireJS loads the data-main

script asynchronously
. So there is a race condition between page load and main.js load. If main.js finishes loading first, it window.onload

will be installed and you will see "render ran". If the page loads first, you won't. Which of these two results matters is generally undefined, but since the example page shown is extremely short, it usually finishes loading before main.js is fetched from the server.

If you want your module to run after the page has loaded, you can add a domReady

module
dependency :

<script src="require.js"></script> <!-- note, no 'data-main' -->
<script>require( ['main'], function() {} );</script>

      



main.js:

define(['domReady!'], function() {
    // ...
});

      

+9


source


This is probably a problem with RequireJS and the fact that the page is already loaded. RequireJS should already be waiting for all files to load, so use the code below.

Example:

console.log("main.js ran");

function render() {
    console.log("render ran");
}

render();

      



If you're 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(){
   ...
});

      

0


source







All Articles