I'm trying to figure out how the unload event works. I'm using a $(window).unload()
handler to send a list of several custom values to my analytics service when the user moves to another page. I make a separate API call to the service for each value.
I'm just wondering if I can rely on my handler running every time till it's finished, or if there'll be some occasions when the loading of the next page's JavaScript will interrupt it before it can register all the values in the list.
The jQuery documentation on .unload() says "It is not possible to cancel the unload event with .preventDefault()." To me this implies that after the browser starts executing your unload handler there's no way to hold it back from loading, parsing and executing the JS of the new page.
But the MDN page on the window.onunload
event says "The resources removal is processed after the unload event occurs."
So does this mean the browser runs a page's unload function till it's finished, and only then scraps it to load the next page's JS?
The onunload event occurs once a page has unloaded (or the browser window has been closed).
Purpose: The beforeunload event triggers right before unloading of the window has begun. unload would trigger while unloading of the window is taking place.
The unload event occurs when the user navigates away from the page. The unload event is triggered when: a link to leave the page is clicked. a new URL is typed in the address bar.
MDN seems to have multiple versions in their site. Here's another one about unload which describes the state of the document during unload.
unload
The unload event is fired when the document or a child resource is being unloaded.
It is fired after:
- beforeunload (cancellable event)
- pagehide
The document is in a particular state:
- all the resources still exist (img, iframe etc.)
- nothing is visible anymore to the end user
- UI interactions are ineffective (window.open, alert, confirm etc.)
- an error won't stop the unloading workflow
As far as I know, async requests (ajax) could possibly be fired but not guaranteed that they will arrive on the server or even get off the browser.
In the context with one of your tags (analytics), it seems like you are trying to know when the user leaves the page.
Why not do a heartbeat/regular ping to the server? The last known ping could be used as an estimate of when the user was last seen on that page.
Or store the time the user left the page inside a cookie, like some sort of "pending report". This can be executed inside unload
. The next time your script meets the cookie, have it parsed for the pending data and send it to the server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With