StackOverflower
StackOverflower

Reputation: 5781

Why windows.onload is executed several times?

I'm binding the window.onload event like this

// It's a little more complex than this, I analyze if there is any other function 
// attached but for the sake of the question it's ok, this behaves the same.
window.onload = myfunction; 

Onload is triggered twice on my local machine a several times on the production server

If I change it by the jQuery equivalent

$jQuery(window).load(myfunction);

It behaves as expected (executed only once).

Could you help me to understand possible reasons why the first option it's not working as supposed?

Thanks!

Upvotes: 5

Views: 12782

Answers (1)

Nicole
Nicole

Reputation: 33227

The parentheses on your assignment — myfunction() — executes your function. You haven't shown what myfunction does, but this means that the return value from that function is being assigned to window.onload, not the function itself. So, I don't know how that is getting executed, unless you have somehow got that to work, like ending the function with return this;

You want

window.onload = myfunction;


Given the nature of window.onload, it seems unlikely that pure browser events alone are making both calls to myfunction. Therefore, a breakpoint inside your function will help you see the call stack. I've included screenshots for Chrome.

Sample code:

var alertme = function() {
    alert("Hello");
}

window.onload = alertme;

function testsecondcall() {
    alertme();
}

testsecondcall();
  1. Open your page in Chrome.
  2. After the page has loaded once, open the Developer Tools panel and put a breakpoint on the line inside your function, then refresh the page.
  3. Check the call stack of both times that it breaks. One will be empty (the actual window.onload). The other should give you some information like the following:

enter image description here

On the right, under "Call Stack", you see alertme is called by testsecondcall

Upvotes: 7

Related Questions