Has fetch() caught up with XMLHttpRequest in JavaScript?

Published on
Updated on

Fetch() vs XHR
Fetch() vs XHR

fetch() is the newer alternative to XMLHttpRequest (or XHR in short) with improved ergonomics, such as integration with promises / async / await and stream support. It was introduced in 2015. Despite that, many popular libraries still support XHR under the hood for AJAX requests. jQuery and Axios are some of them.

Where fetch() has caught up (or even surpassed XHR)

fetch() has come a long way since 2015. In most regards fetch() is very mature and can do many things that XMLHttpRequest can do or even exceed it. Including:

Where fetch() hasn't caught up

Despite the last example, fetch() still doesn't truly support upload progress. XHR, on the other hand, supports both upload and download progress:

const xhr = new XMLHttpRequest(); xhr.upload.onprogress = (e) => { console.log(`${e.type}: ${e.loaded} bytes uploaded`); } xhr.onprogress = (e) => { console.log(`${e.type}: ${e.loaded} bytes downloaded`); } xhr.onload = () => { console.log("DONE", xhr.response); }; const formData = new FormData(); formData.set("file", new Blob(["Some file content ".repeat(100000)], { type: 'text/plain' })); console.log("Starting request"); xhr.open("POST", "/api/test?responseSize=50000"); xhr.send(formData);

Also, in addition to this, XHR supports synchronous requests. Although deprecated and discouraged to be used, it might have some use cases in specific situations.

These two reasons may explain why many popular libraries still lean more towards the old XHR.

Conclusion

fetch() is now very mature and provides most of the (or even surpassing in some regards, such as with streaming and keepalive) XMLHttpRequest functionality. However it doesn't support true upload progress and synchronous requests. While both (especially the last one) aren't the most used features, library makers usually want to cover all the use cases, which isn't surprising. So is a safer choice to keep the old XMLHttpRequest at least as a fallback. For most general use cases fetch() is a better choice due to its ergonomics, promise integration, stream and keepalive support.





Read previous



UP
This site uses cookies. By continuing to use this website, you agree to their use. To find out more, including how to control cookies, see here: Privacy & cookies.