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?
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.
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.
Note: The load() method deprecated in jQuery version 1.8. It was completely removed in version 3.0.
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.
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() {
// ...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With