Today I Learned - Rocky Kev

TIL problem with AJAX

POSTED ON:

TAGS:

Today I learned about the problem with AJAX/XMLHttpRequest(XHR).

Today, we use fetch, but we used to do this:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
var response = JSON.parse(xhr.responseText);
console.log("Temperature(K): " + response.main.temp);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);

via https://stackoverflow.com/a/21318133/4096078

What was the issue?

Synchronous XHR is harmful for performance because the event loop and main thread is blocked until the request is finished, resulting in the page hanging until the data becomes available. fetch is a much more effective and efficient alternative with a simpler API, and has no support for synchronous fetching of data.

While synchronous XHR is only used on 2.5% of mobile pages and 2.8% of desktop pages, its continued use—no matter how small—is still a signal that some legacy applications may be relying on this outdated method that harms the user experience.

The solution:

fetch is a much more ergonomic alternative that lacks synchronous functionality by design. Your pages will perform better without synchronous XHR, and we hope someday to see this number fall to zero.

via https://almanac.httparchive.org/en/2022/javascript?utm_source=pocket_reader


Related TILs

Tagged:

TIL problem with AJAX

Synchronous XHR is harmful for performance because the event loop and main thread is blocked until the request is finished, resulting in the page hanging until the data becomes available. fetch is a much more effective and efficient alternative with a simpler API, and has no support for synchronous fetching of data.

TIL a quick recipe involving Axios and Cheerio

A quick recipe to http request an api and use cheerio to web-scrape it

TIL a quick recipe involving Axios and Cheerio

A quick recipe to http request an api and use cheerio to web-scrape it