window.onload 没有调用函数
window.onload not calling function
有了这个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
console.log("main.js ran");
function render() {
console.log("render ran");
}
window.onload = render;
我希望控制台输出显示:
main.js ran
render ran
"main.js ran" 按预期显示,但 "render ran" 未记录。渲染函数永远不会被调用。为什么不呢?
这可能是 RequireJS 的问题以及页面已经加载的事实。 RequireJS 应该已经在等待所有文件加载,所以使用下面的代码。
示例:
console.log("main.js ran");
function render() {
console.log("render ran");
}
render();
如果您正在尝试等待 HTML 元素加载,请使用 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(){
...
});
RequireJS loads the data-main
script asynchronously。因此,页面加载和 main.js 加载之间存在竞争条件。如果 main.js 先完成加载,将设置 window.onload
,您将看到 "render ran"。如果页面首先完成加载,则不会。这两种结果中的哪一种发生通常是不确定的,但由于您提供的示例页面非常短,它通常会在 main.js 从服务器获取之前完成加载。
如果您希望您的模块在页面加载后 运行,您可以添加对 domReady
module 的依赖:
<script src="require.js"></script> <!-- note, no 'data-main' -->
<script>require( ['main'], function() {} );</script>
main.js:
define(['domReady!'], function() {
// ...
});
有了这个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
console.log("main.js ran");
function render() {
console.log("render ran");
}
window.onload = render;
我希望控制台输出显示:
main.js ran
render ran
"main.js ran" 按预期显示,但 "render ran" 未记录。渲染函数永远不会被调用。为什么不呢?
这可能是 RequireJS 的问题以及页面已经加载的事实。 RequireJS 应该已经在等待所有文件加载,所以使用下面的代码。
示例:
console.log("main.js ran");
function render() {
console.log("render ran");
}
render();
如果您正在尝试等待 HTML 元素加载,请使用 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(){
...
});
RequireJS loads the data-main
script asynchronously。因此,页面加载和 main.js 加载之间存在竞争条件。如果 main.js 先完成加载,将设置 window.onload
,您将看到 "render ran"。如果页面首先完成加载,则不会。这两种结果中的哪一种发生通常是不确定的,但由于您提供的示例页面非常短,它通常会在 main.js 从服务器获取之前完成加载。
如果您希望您的模块在页面加载后 运行,您可以添加对 domReady
module 的依赖:
<script src="require.js"></script> <!-- note, no 'data-main' -->
<script>require( ['main'], function() {} );</script>
main.js:
define(['domReady!'], function() {
// ...
});