javascript window.onload 事件不会触发或“如何正确初始化 js 项目?”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19393081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
window.onload event doesn't fires or "how to properly initialize js project?"
提问by msgmaxim
This problem seems to be common, though I couldn't find the answer.
这个问题似乎很常见,但我找不到答案。
I've got this simple html with the only canvas tag
我有这个带有唯一画布标签的简单 html
<!doctype html>
<head>
<meta charset = "utf-8">
<script src="js/script.js"></script>
<title>Title</title>
</head>
<body>
<canvas id = "canvas"></canvas>
</body>
</html>
and in script.js I'm trying to catch window.onload event:
在 script.js 中,我试图捕捉 window.onload 事件:
window.onload = init;
function init(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillRect(50, 20, 150, 150);
}
But nothing happens. I assume that the html is loaded even before the first line of js executed.
但什么也没有发生。我假设 html 甚至在 js 的第一行执行之前就已经加载了。
So I found that the alternative to onload event would be to put script definition in the end of the body, so when script being executed the window is supposed to be loaded alreade. So I did like this:
所以我发现 onload 事件的替代方法是将脚本定义放在正文的末尾,所以当脚本被执行时,窗口应该被加载。所以我是这样的:
<!doctype html>
<head>
<meta charset = "utf-8">
<!-- gone -->
<title>Title</title>
</head>
<body>
<canvas id = "canvas"></canvas>
<script src="js/script.js"></script> <!-- inserted -->
</body>
</html>
and
和
<!-- window.onload = init; -->
init() <!-- inserted -->
function init(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillRect(50, 20, 150, 150);
}
And in a way it works (draws rectangle) , but gives me an error Uncaught ReferenceError: context is not defined.
并且在某种程度上它起作用(绘制矩形),但给了我一个错误Uncaught ReferenceError: context is not defined。
So my question is what I'm doing wrong? I'm also wonderring if there is a better way to do this.
所以我的问题是我做错了什么?我也想知道是否有更好的方法来做到这一点。
P.S. I tend not to use jquery...
PS我倾向于不使用jquery ...
EDITED:the error with context has nothing to do with the code above, although I still don't like the idea of putting the link to js file in the end of the body...
已编辑:上下文错误与上面的代码无关,尽管我仍然不喜欢将 js 文件的链接放在正文末尾的想法......
采纳答案by enhzflep
Here, try the following code. The key points being:
在这里,尝试以下代码。关键点是:
(1) You can assign more than 1 function to be run when the onload event fires. (2) You can attach them whereever you please. They all still get called when the attached event fires. However - I don't think there is a guarantee that functions will be executed in the same order that they were attached. Keep this in mind when attaching multiple functions to a single event using addEventListener.
(1) 当 onload 事件触发时,您可以分配 1 个以上的函数来运行。(2) 您可以随心所欲地附上它们。当附加事件触发时,它们仍然会被调用。但是 - 我认为不能保证函数会按照它们附加的顺序执行。使用 addEventListener 将多个函数附加到单个事件时,请记住这一点。
Anyhow, the output is:
无论如何,输出是:
created with function called from **test.js**
created with function called from test.html
created with function called from **test.js**
test.html
测试.html
<!doctype html>
<html>
<head>
<script src='test.js'></script>
<script>
window.addEventListener('load', mInlineJsLoadFunc, false);
function mInlineJsLoadFunc()
{
var div = document.createElement('div');
div.appendChild( document.createTextNode('created with function called from test.html') );
document.body.appendChild(div);
}
</script>
<style>
</style>
</head>
<body>
</body>
<script src='test.js'></script>
<html>
test.js
测试.js
window.addEventListener('load', mExternalJsLoadFunc, false);
function mExternalJsLoadFunc()
{
var div = document.createElement('div');
div.appendChild( document.createTextNode('created with function called from **test.js**') );
document.body.appendChild(div);
}
回答by Anurag Uniyal
I don't see a reason why it should not work e.g. here is a simple jsfiddleonload
with alert
我没有看到它不应该工作的原因,例如这里是一个带有警报的简单 jsfiddleonload
Though you don't need to do it in two steps and you can just write
虽然你不需要分两步做,你可以写
window.onload = function() {
alert(1)
}
If this is not working in your case then debug or log to console what is the value of window.onload
, may be some other library is overriding it, that is why it is better to use some library like jQuery
如果这在您的情况下不起作用,则调试或登录到控制台的值是什么window.onload
,可能是其他库覆盖了它,这就是为什么最好使用像 jQuery 这样的库
回答by august0490
Move the window.onload line to the end of the javascript file or after the initial function and it will work:
将 window.onload 行移动到 javascript 文件的末尾或初始函数之后,它将起作用:
function yourFunction(){
// ...
}
// ...
// at the end of the file...
window.onload = yourFunction;
window.onresize = yourFunction;
But it's a best practice if you don't replace the onload too. Instead attach your function to the onload event:
但如果您不更换 onload 也是最佳实践。而是将您的函数附加到 onload 事件:
function yourFunction(){
//...
}
// ...
// at the end of the file...
window.addEventListener ?
window.addEventListener("load",yourFunction,false)
:
window.attachEvent && window.attachEvent("onload",yourFunction);
That worked for me and sorry for my english.
这对我有用,对我的英语很抱歉。