下面的代码片段来自本书 JavaScript。绝对指南.
我有一些问题。从我的角度来看,我不认为在任何情况下都必须要使用 onLoad
函数的一部分。
我认为这段代码应该作为全局javascript使用,而不是作为事件处理程序的一部分。如果它在按钮的事件处理程序中被调用,那么窗口的加载事件肯定已经被触发。因此,注册的函数将不会被调用。
但是,如果它被用作全局的javascript, onLoad.loaded
始终为假,当 onLoad
函数被调用。
为什么不直接在窗口上注册加载事件,而不是检查是否有 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
脚本定义的函数可以从任何地方调用,以后,甚至从按钮事件处理程序等。