How does onunload impact page performance

255 Views Asked by At

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?

2

There are 2 best solutions below

2
On

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/…

0
On

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