[removed] not calling function

2019-02-07 11:41发布

问题:

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?

回答1:

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() {
    // ...
});


回答2:

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(){
   ...
});