|Mozilla's Fetch API Could Clean Up AJAX|
|Written by Ian Elliot|
|Wednesday, 18 March 2015|
One of the foundations of AJAX, it is what made it possible, is the XMLHttpRequest method, which allows you to programatically download new data and resources. It isn't perfect but it seems to work. Mozilla thinks that its new Fetch API is the next logical step.
Mozilla is of the opinion that XMLHttpRequest XHR is not quite as good as it should be. Specifically:
The new Fetch API makes use of the primitives that the HTTP protocol uses. At its simplest you can call the new fetch function with a URL and get back a promise object that you can use to process the downloaded resource when the transfer is complete.
However, you can go well beyond this simple scenario. As well as the fetch method, there are also Headers, Request and Response which wrap the basic HTTP concepts.
You can create a Header object to specify all of the usual HTTP headers to be sent in a request. You also get a Header object as part of a response.
To get a response you create a Request object and specify a URL, HTTP method e.g. GET, POST etc. and headers and use this in a call to fetch. This returns a Response object when its promise object completes.
Both Requests and Response objects can have body data. i.e. the payload of the transaction. Body data can be any of:
One oddity that might trip up the innocent programmer is that a Response body can only be read once. There is a flag you can check to see if it is safe to read the body or not. Why do this? The reason is that the intention is to move to a stream-based mode of reading that would allow data to be read as soon as it was available.
The features are all capable of working with CORS for cross-origin requests. The API is also tailored to being used with a ServiceWorker to offload the processing from the UI thread.
At the moment there is no way to abort a request or to report its progress. These seems to be difficult features to fit in with a promise based mechanism.
At the moment the Fetch API is in Firefox 39 (currently Nightly) and Chrome 42 (currently Dev) and there is a Fetch polyfill. There's no word on what Microsoft or Apple are doing about Fetch - the compatibility table simply says "not supported" - so that looks like another potential browser split. The the API is also a work in progress at the WHATWG and not at W3C - could this mean a potential standards split as well?
Thank goodness for polyfills.
To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin, or sign up for our weekly newsletter.
or email your comment to: firstname.lastname@example.org
|Last Updated ( Wednesday, 18 March 2015 )|