Here's an example for registering a function on document load (most of it taken from JavaScript: The Definitive Guide):
"use strict";
//run function f when document is loaded
function onLoad(f) {
if (onLoad.loaded) // If already loaded
window.setTimeout(f, 0);
else if (window.addEventListener)
window.addEventListener("load", f, false);
}
onLoad.loaded = false;
onLoad(function() { onLoad.loaded = true; });
onLoad(myfunc);
function myfunc() {
console.log("Hello, world!");
}
I'm getting confused with the line onLoad(function() { onLoad.loaded = true; });. I can tell that it's self-invocation, but using the function name again baffles me. Why is it needed? I find that if I do only (function() { onLoad.loaded = true; }); then also the output is the same.
Finally, I can get the same output by using:
function myfunc() {
console.log("Hello, world!");
}
window.onload = (function() {window.setTimeout(myfunc, 0);});
How is my code better/worse?