使用 "JavaScript: The Definite Guide" 中的这个 onLoad 函数有什么意义?
What's the point of using this onLoad function from "JavaScript: The Definite Guide"?
下面的代码片段来自 JavaScript 书:权威指南。
我对此有一些疑问。从我的角度来看,我预计不会出现任何必须使用 onLoad
函数的情况。
我认为这段代码必须用作全局 javascript 而不是事件处理程序的一部分。如果在按钮的事件处理程序中调用它,则 window 上的加载事件必须已经触发。因此,永远不会调用已注册的函数。
但是,如果它被用作全局javascript,onLoad.loaded
在调用onLoad
函数时总是false。
为什么不直接在 window 上注册加载事件,而不是检查 onLoad.loaded
是真还是假?
// Register the function f to run when the document finishes loading.
// If the document has already loaded, run it asynchronously ASAP.
function onLoad(f) {
if (onLoad.loaded) // If document is already loaded
window.setTimeout(f, 0); // Queue f to be run as soon as possible
else if (window.addEventListener) // Standard event registration method
window.addEventListener("load", f, false);
else if (window.attachEvent) // IE8 and earlier use this instead
window.attachEvent("onload", f);
}
// Start by setting a flag that indicates that the document is not loaded yet.
onLoad.loaded = false;
// And register a function to set the flag when the document does load.
onLoad(function() {
onLoad.loaded = true;
});
我觉得你对使用场景理解有误
你是对的,上面的代码片段应该在启动时执行,在网页完成加载之前,以便 onLoad.loaded
被准确分配。
但是,脚本定义的 onLoad
函数以后可以从任何地方调用,甚至可以从按钮事件处理程序等调用。
下面的代码片段来自 JavaScript 书:权威指南。
我对此有一些疑问。从我的角度来看,我预计不会出现任何必须使用 onLoad
函数的情况。
我认为这段代码必须用作全局 javascript 而不是事件处理程序的一部分。如果在按钮的事件处理程序中调用它,则 window 上的加载事件必须已经触发。因此,永远不会调用已注册的函数。
但是,如果它被用作全局javascript,onLoad.loaded
在调用onLoad
函数时总是false。
为什么不直接在 window 上注册加载事件,而不是检查 onLoad.loaded
是真还是假?
// Register the function f to run when the document finishes loading.
// If the document has already loaded, run it asynchronously ASAP.
function onLoad(f) {
if (onLoad.loaded) // If document is already loaded
window.setTimeout(f, 0); // Queue f to be run as soon as possible
else if (window.addEventListener) // Standard event registration method
window.addEventListener("load", f, false);
else if (window.attachEvent) // IE8 and earlier use this instead
window.attachEvent("onload", f);
}
// Start by setting a flag that indicates that the document is not loaded yet.
onLoad.loaded = false;
// And register a function to set the flag when the document does load.
onLoad(function() {
onLoad.loaded = true;
});
我觉得你对使用场景理解有误
你是对的,上面的代码片段应该在启动时执行,在网页完成加载之前,以便 onLoad.loaded
被准确分配。
但是,脚本定义的 onLoad
函数以后可以从任何地方调用,甚至可以从按钮事件处理程序等调用。