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


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?




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() {

window.onload = alertme;

function 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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.