Here is a helpful snippet for handling AJAX calls effectively. Execute this code as soon as possible to ensure it works for subsequent AJAX requests.
It's important to address failed requests promptly as they can compound if left unresolved. This script allows for automatic retries, incrementing with each failed attempt.
Keep in mind that you may need to make adjustments to retrieve responses from nested requests once they succeed.
// Override 'send' with 'open' to intercept requests early.
XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;
// Track retry attempts per request to prevent infinite loops.
XMLHttpRequest.prototype._maxRetry = 5;
XMLHttpRequest.prototype._currentRetry = 0;
XMLHttpRequest.prototype.open = function open(...args) {
if (!this._currentRetry) {
console.log('REQUEST CAPTURED.');
}
this.addEventListener('error', () => {
// Abort the current request.
this.abort();
// Check the number of retries.
if (this._currentRetry >= this._maxRetry) {
console.log('MAX RETRY REACHED.');
return;
}
console.log(`RETRYING ${this._currentRetry} of ${this._maxRetry}.`);
// Create a new request instance.
const req = new XMLHttpRequest();
// Copy updated retry numbers to the new instance.
req._maxRetry = this._maxRetry;
req._currentRetry = this._currentRetry + 1;
req.responseType = this.responseType;
// Send the new request using previous arguments.
req.open(...args);
req.send();
});
// Call the original 'open' method.
this._open(...args);
};
const test = new XMLHttpRequest();
test.open('GET', 'https://asfashdg');
test.send();