Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 would expect the console output to show:

main.js ran
render ran

The "main.js ran" shows as expected, but "render ran" doesn't get logged. The render function never gets called. Why not?

like image 875
vocalionecho Avatar asked Apr 13 '15 02:04

vocalionecho


People also ask

How do you call a function on window onload?

The first approach for calling a function on the page load is the use an onload event inside the HTML <body> tag. As you know, the HTML body contains the entire content of the web page, and when all HTML body loads on the web browser, it will call the function from the JavaScript.

How do you trigger onload?

Yeah, you can use a click event called onLoad() . Just use the setTimeout() method in jquery. It will call a click function without clicking it.

Is window onload deprecated?

Note: The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0.

What does the window onload function do?

The onload property processes load events after the element has finished loading. This is used with the window element to execute a script after the webpage has completely loaded.


1 Answers

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() {
    // ...
});
like image 121
radiaph Avatar answered Oct 11 '22 08:10

radiaph