Is the unload event handler a guaranteed completion before the next page is wiped clean?

I am trying to figure out how the unload event works. I use the $(window).unload() handler to send a list of several user values โ€‹โ€‹to my analytic service when the user goes to another page. I am making a separate API call for the service for each value.

I'm just wondering if I can count on my handler to work every time until it finishes, or if there will be times when loading the next page will interrupt it before it can register all the values โ€‹โ€‹in the list.

The jQuery documentation for .unload () reads: "Cannot cancel unload event with .preventDefault ()." For me, this means that after the browser starts executing your upload handler, there is no way to keep it from loading, parsing, and executing JS of a new page.

But the MDN page in the window.onunload event says: "Removing resources is processed after the unload event occurs."

Does this mean that the browser runs the page upload function before it is completed, and only then removes it to load the next JS page?

+6
source share
1 answer

MDN seems to have several versions on its site. Here is another one about unloading, which describes the state of the document during unloading.

unload

The unload event is triggered when a document or child resource is unloaded.

It starts after:

  • beforeunload (cancel event)
  • pagehide

The document is in a certain state:

  • all resources still exist (img, iframe, etc.)
  • nothing is displayed to the end user
  • Interface interactions are inefficient (window.open, alert, confirm, etc.)
  • the error will not stop the unloading workflow

As far as I know, asynchronous requests (ajax) can be launched, but are not guaranteed that they will arrive on the server or even exit the browser.


In the context of one of your tags (analytics), it seems that you are trying to find out when the user leaves the page.

  • Why not do a heartbeat / regular ping on the server? The last known ping can be used as an estimate of when the user was last seen on this page.

  • Or save the time when the user left the page inside the cookie, for example, some kind of โ€œpending reportโ€. This can be done inside unload . The next time your script encounters a cookie, ask it to analyze the pending data and send it to the server.

+3
source

All Articles