XMLHttpRequest (XHR) Vs Fetch API

Hi,

I discovered this webpage
developer.mozilla.org/en-US/…/XMLHttpRequest

Where it say

The Fetch API is the modern replacement for XMLHttpRequest.

Without further explain on why so…

Did you (yourself) migrated from XHR to The Fetch API ? and is it better ? or do you know any (not bias) article about it ?

What about performances etc…

Thanks

cross-posted onlemmy.world/post/14707833

Ember_Rising,

Also, you can use Wretch for a really neat builder pattern to make requests.

elbywan.github.io/wretch/

walter_wiggles,

I think of XHR as more of a low-level API. Most of the time though you don’t need access to those low-level details.

The fetch API is bit higher level and nicer to work with.

Max_P, (edited )
@Max_P@lemmy.max-p.me avatar

XHR is absolutely ancient. Like, I used it on Internet Explorer 6 era websites. Using a 3x3 table with images in all 8 outer cells to make rounded corners.

It still works but is so old it can’t really be updated. It’s entirely callback driven so no async. It’s not even async by default if I recall correctly, it just hangs the browser.

The Fetch API was designed to modernize what XHR does, and does so well. Now, a simple get request you can pretty much await fetch(…) whereas the XHR one is probably 20-40 lines of code and most people end up using a library to deal with it, or write their own little wrapper for it. It supports promises natively.You can stream very large files without loading it all in memory. There’s nothing XHR can do that fetch can’t do, and usually does it better too. For most use cases the performance will be the same, network IO is orders of magnitude slower than JavaScript execution. But the API being better probably does lead to better performance by not doing unnecessary things and possibly processing data as it arrives instead of all in one go when the download is finished.

It’s a modern replacement because it’s literally what it was designed to be. Try both and it’ll be abundantly clear why.

Corsair,
@Corsair@programming.dev avatar

Thanks @Max_P weird because I can use XHR as async… see: developer.mozilla.org/en-US/docs/Web/API/…/openopen(method, url, async)

SteveTech,

Sure it let’s you use it asynchronously, but it predates and is not really compatible with JavaScript’s async/Promise API.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • webdev@programming.dev
  • kavyap
  • Durango
  • osvaldo12
  • khanakhh
  • mdbf
  • DreamBathrooms
  • ngwrru68w68
  • magazineikmin
  • thenastyranch
  • cubers
  • Youngstown
  • slotface
  • rosin
  • GTA5RPClips
  • megavids
  • anitta
  • tacticalgear
  • modclub
  • ethstaker
  • cisconetworking
  • InstantRegret
  • everett
  • provamag3
  • normalnudes
  • Leos
  • tester
  • JUstTest
  • lostlight
  • All magazines