Difference between onbeforeunload and onunload

Solution 1:

onunload is responsible for executing an instruction when the page is closed. It also causes issue with IE and AJAX.

onbeforeunload is more efficient because it does not run in competition with the actual closing of the window and is triggered before onunload

I know Opera used to not acknowledge onbeforeunload - not sure if they've fixed that, but I always register the listener for both to be safe:

window.onunload = window.onbeforeunload = (function(){...

Solution 2:

Adding with AlienWebguy's ans, to avoid dual calls at the browsers that support both events,

var onBeforeUnLoadEvent = false;

window.onunload = window.onbeforeunload= function(){
if(!onBeforeUnLoadEvent){
  onBeforeUnLoadEvent = true;
  //your code here
  }
};

Solution 3:

onbeforeunload:

  • Called before unloading begins
  • MDN tells me you can cancel the closing of the page using event.preventDefault();
  • or by returning a non-void value (ie a value != 0), the page will pop up a confirmation dialog that allows the user to choose to cancel the close
  • MDN also says Opera 12 and up support onbeforeunload - looks like its supported it for a while now

onunload:

  • Called after unloading has begun, but before any resource deallocation (its not clear to me what exactly is done during this period)
  • Its too late to cancel the page close at this point

The only reason I can think of why you would want to use onunload over onbeforeunload would be where your onunload code could take some significant time, and don't want the user to see a window that hangs while closing.

Solution 4:

One significant difference (other than cancelability) between the onbeforeunload and onunload is that the former is triggered for download links and the latter is not. Example: <a href="https://somewhere.com/thething.zip">download</a> will trigger the onbeforeunload handler, but not the onunload.