window.onload不能调用函数

window.onload不能调用函数

问题描述:

有了这个index.html:

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>

和这个main.js

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

main.js运行按预期显示,但渲染运行不会被记录。渲染函数永远不会被调用。为什么不呢?

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

RequireJS异步加载 data-main 脚本。因此,页面加载和main.js加载之间存在争用条件。如果main.js首先完成加载,则将设置 window.onload ,您将看到render ran。如果页面首先完成加载,则不会。出现这两种结果中的哪一种通常是不确定的,但由于您给出的示例页面非常短,通常会在从服务器获取main.js之前完成加载。

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.

如果您希望模块在页面加载后运行,您可以添加对 domReady module

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