Difference between onbeforeunload and onunload Difference between onbeforeunload and onunload javascript javascript

Difference between onbeforeunload and onunload


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


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  }};


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.