Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when an XMLHttpRequest is aborted?

  • Will an aborted XMLHttpRequest still download the response from the server?
  • At what point in the request lifecycle does it differ from a regular request?
  • Do different browsers behave differently?
  • Is it bad practise to abort requests?
like image 234
Trent Avatar asked Aug 26 '16 03:08

Trent


1 Answers

  • No, the download will (should) cancel (does in my browser at least)
  • When a request is aborted, its readyState is changed to XMLHttpRequest.UNSENT (0) and the request's status code is set to 0. -- MDN

  • No, at least hopefully not. They should be following the spec.
  • In my opinion, definitely not. It's a waste of bandwidth and other resources to have requests you no longer need running in the background. Much better to abort them.

Two recent use-cases from personal experience:

  • A table with various parameters for filtering. Depending on the parameters selected, the resulting request sometimes took a while to complete. If you selected a slow set of parameters A, and then a fast set of parameters B before A completed, you'd first see the results of B in the table, but then A would eventually complete and "replace" the contents of the table so you'd suddenly see A instead.
    Solution: Abort the previous incomplete request before starting the next one.
  • SPA with pages with sometimes long running requests, for example the previously mentioned table. When navigating away to a different page, there were sometimes several requests running in the background for stuff no longer needed.
    Solution: Register those requests to be aborted when the page/component was unmounted.
like image 190
Svish Avatar answered Oct 06 '22 00:10

Svish