I have site that is doing a bunch of work in a window.onunload
handler. I am working on optimizing it but I don't really understand how it impacts my page performance. It seems like it blocks reloading the page or navigating to another URL on the same domain, but it doesn't seem to block cross domain navigation. It also seems to cause performance issues intermittently on Chrome but is more consistently reproducible on IE. Can someone explain how window.onunload
impacts site performance or point me to the spec that does?

- 12,892
- 6
- 42
- 45
-
1Never tried it, but you could try to put the logic in a service worker – baao Jun 06 '18 at 22:13
-
Here’s a link you may find useful https://stackoverflow.com/questions/20180251/when-to-use-window-onload/20180282 – Anthony Letizia Jun 06 '18 at 22:24
2 Answers
It would be very intresting to see a speed test in different browsers using windows.onload vs. other methods. Maybe I’ll test it out tomorrow and get back to you.
Until then, here’s a link you may find useful
stackoverflow.com/questions/20180251/when-to-use-window-onload/…

- 56
- 9
-
This is more of a comment than a solution. Please save answers for actual attempts at a solution. Though your contribution is greatly appreciated! – Ryan Wheale Jun 06 '18 at 22:39
-
The main issue with unload
handlers is the analytics trackers that do synchronous XHR to send some last portion of tracking data. The synchronous XHR is blocking the navigation to the next page until it completes, hence it's a massive anti-pattern.
Instead, navigator.sendBeacon
should be used (https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon). This API was created to address precisely that issue, but since it's new, it's not universally supported (most notably, IE11 lacks support).
(Sync XHR has been used for a long time for this use case to guarantee the execution of the HTTP call; async code in unload handlers will not be executed, and async XHRs issued before navigation might be cancelled upon navigation.)

- 38,512
- 12
- 92
- 130