Skip to content

Instantly share code, notes, and snippets.

@vneri
Created May 13, 2020 12:35
Show Gist options
  • Save vneri/028a11cb12b454d7a3dc5902954cc548 to your computer and use it in GitHub Desktop.
Save vneri/028a11cb12b454d7a3dc5902954cc548 to your computer and use it in GitHub Desktop.
Script for counting open AJAX and fetch calls
// intercepts AJAX and fetch calls and provides a global status on open calls
var AjaxFetchWatcher = {};
AjaxFetchWatcher.countOfOpenRequests = 0;
AjaxFetchWatcher.stillOpen = function(){
return AjaxFetchWatcher.countOfOpenRequests > 0;
};
// intercept AJAX
// thank you https://stackoverflow.com/questions/10783463/javascript-detect-ajax-requests
(function() {
var proxied = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
AjaxFetchWatcher.countOfOpenRequests += 1;
var pointer = this;
var intervalId = window.setInterval(function(){
if (pointer.readyState != 4){
return;
}
AjaxFetchWatcher.countOfOpenRequests -= 1;
//Here is where you can add any code to process the response.
//If you want to pass the Ajax request object, pass the 'pointer' below
clearInterval(intervalId);
}, 0.3);
return proxied.apply(this, [].slice.call(arguments));
};
})();
// intercept fetch
(function() {
var proxied = window.fetch;
window.fetch = function() {
AjaxFetchWatcher.countOfOpenRequests += 1;
var pointer = this;
return proxied([].slice.call(arguments)).then(a => {
AjaxFetchWatcher.countOfOpenRequests -= 1;
}
).catch( a=>
{
AjaxFetchWatcher.countOfOpenRequests -= 1;
}
);
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment