0

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?

1 Answer 1

2

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.

It isn't a self-invocation.

It is a call to the function onLoad (previously defined) with one argument (which is a function expression).

Finally, I can get the same output by using… How is my code better/worse?

Your code will:

  • Only support a function function to be called when the load event fires. If you try to assign another function, it will overwrite the previous one instead of setting up two functions to be called when the event fires.
  • Won't call the function immediately (or at all) if the load event has already fired (so you can't use it in a script that can be dynamically added to the page as well as being used normally)
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer! Now it makes complete sense. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.