Has fetch() caught up with XMLHttpRequest in JavaScript?

Published 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 as part of the ES6. Despite of that, many popular libraries still use 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. Including:

Where fetch() hasn't caught up

Despite of 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", "/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) 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 the old XMLHttpRequest is a safer choice in this regard.





UP
Read previous



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.