9

I'm using in a project the following code which is not working:

window.onload=function(){
 //code here
};

but if I add at the end () it works:

window.onload=function(){
 //code here
}();

My question is, what's the difference? What does the () at the end?

I presume that the first one doesn't work because somewhere else the "onload" has been already called killing this one.

Would it have the same behaviour if I always use the second option ?

4 Answers 4

11

() at the end of function, calls this function immediately after declaration

window.onload=function(){
 //code ehere
}() // function is called 

And in this case

window.onload=function(){
 //code here
}; 

function will be called after

window.onload()
Sign up to request clarification or add additional context in comments.

4 Comments

Would () be like a document ready ? or still would be a document onload
@themazz window.onload will be the result of onload function execution. See furas's answer
@themazz read here, about onload global function developer.mozilla.org/en-US/docs/Web/API/…
@themazz you should declare window.onload function before page is loaded, e.g. in <script> tag on page
5

When you have () after a lambda function such as that, it means you're calling the function immediately on that line.

So, for example,

var x=function() {
    return 5;
}();
console.log(x);

would log 5 in the console. In the case of

window.onload=function() {
    //code here
}();

that function most likely returns another function that gets called when the page loads.

For example,

window.onload=function() {
    return function() {
        console.log("Hello!");
    };
}();

will log "Hello!" in the console when the page loads.

Comments

4

function is assigned to onload

window.onload=function(){
 //code ehere
};

result of function is assigned to onload

window.onload=function(){
 //code ehere
}();

2 Comments

just me or you copied first code block from Ilya? ;) (notice the "ehere").
did not notice that I copy code from answer and not from question :)
1

With the () the function you define is called immediately. In that case, it better return a function to assign to window.onload.

Comments

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.