The code snippet below is from the book JavaScript: The Definite Guide.
I have some questions about it. From my point of view, I don't anticipate any scenario where there is a must to use the onLoad
function.
I think that this chunk of code has to be used as global javascript instead of as part of an event handler. If it is invoked in an event handler of a button, the load event on window must have already been triggered. As a result, the registered function will never be invoked.
However, if it is used as the global javascript, onLoad.loaded
is always false when the onLoad
function is invoked.
Why not just register the load event on window, instead of checking whether onLoad.loaded
is true or false?
// 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;
});
I think you misunderstand the usage scenario.
You are right, the above snippet should be executed on startup, before the webpage completes loading, so that onLoad.loaded
is accurately assigned.
However, the onLoad
function that is defined by the script can be invoked from anywhere, later, even from button event handlers etc.