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