也许这是一个重复的问题,但我想问。
我想制作一个不使用第三方库的JS应用程序,以便学习浏览器中的JS事件。
所以我这样构建我的应用程序:
var APP = APP || (function (global) {
return {
digitsField: {},
// other properties, methods
init: function (config) {
try {
this.digitsField = global.getElementById('digitsField');
return this;
} catch (error) {
console.log(error.message);
return false;
};
}
};
} (window.document));
我的 html 页面看起来像这样:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
</head>
<body onload="APP.init({});">
<input type="text" value="0" class="textField" readonly="true" id="digitsField"/>
// other html tags
</body>
</html>
虽然我发送window.document
到我的直接函数,digitsField
在加载页面或直到我调用APP.init()
之前,标签仍未定义用于其他工作功能。我还注意到 Firebug 中的 DOM 选项卡中有一个全局行专门用于 onload
事件使全局命名空间变得困惑。也许有更好的初始化方法APP.digitsField
不使用 window.onload
到标签对象事件或第三方库?
让我知道你的想法。
最佳答案
加载所有内容(包括外部资源)时,将触发窗口 onload 事件。然而,您应该只需要等待 DOM 加载,因此您可以将处理程序附加到 DOMContentLoaded 事件:
document.addEventListener("DOMContentLoaded", function() {
// code...
});
这应该适用于比 IE8 更新的浏览器(即 IE9 及更高版本)。
关于javascript - 我应该使用 window.onload 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27888326/