XMLHttpRequest vs Fetch API
XMLHttpRequest vs Fetch API — Comparative Analysis
When discussing HTTP requests in JavaScript, we have two main built-in options: XMLHttpRequest
(XHR) and Fetch API
. Although both serve the same purpose - to receive or send network data - their implementation methods and capabilities differ significantly. In this article, we'll conduct a comparative analysis to examine their differences, advantages, and disadvantages from a professional perspective.
// XMLHttpRequest (XHR)
const xhr = new XMLHttpRequest(); xhr.open("GET", url);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();
// Fetch API
fetch(url)
.then(response => response.json())
.then(data => console.log(data));
Opinion: The Fetch API clearly has a simpler, shorter, and more readable structure, especially when using async/await.
Conclusion: The Fetch API is more compatible with modern JavaScript workflows.
progress
events, configurable timeouts, abort()
method.AbortController
can be used). // Fetch cancellation
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch(url, { signal: controller.signal });
} catch (error) {
if (error.name === "AbortError") {
console.log("Request timed out");
}
}
Conclusion: XHR provides more control "out of the box." With Fetch, you need to add it manually.
responseText
(text) or responseXML
. For JSON, requires JSON.parse()
.json()
, text()
, blob()
, formData()
, etc. - simple and convenient.Conclusion: Fetch has a simpler and more convenient API for data parsing.
Conclusion: If you're targeting older browsers, XHR might still be necessary.
Criterion | XMLHttpRequest | Fetch API |
---|---|---|
Promise support | No | Yes |
Code simplicity | Hard to read, callback-heavy | Simple and async-friendly |
Timeout / Abort | Supported | Requires AbortController |
Progress event | Supported | Not supported |
Support in old browsers | Full | Partial (no IE) |
Final conclusion: In modern applications where IE support isn't mandatory, the Fetch API
is clearly the winner. It's simple, readable, cleaner, and fully compatible with modern async code. While XMLHttpRequest
remains useful in certain cases where you need more control or support for older browsers.