Skip to content

Instantly share code, notes, and snippets.

@gkobilansky
Last active February 22, 2018 17:18
Show Gist options
  • Save gkobilansky/a4bbe87661cd4c367edc563e05e73aae to your computer and use it in GitHub Desktop.
Save gkobilansky/a4bbe87661cd4c367edc563e05e73aae to your computer and use it in GitHub Desktop.
// We look for two things when checking the loading state: 1. Are there any open XMLHttpRequests? 2. Are there any DOM elements with the word loading either in their class or id?
//If no we call our callback function. If yes, we rerun checkLoadingState once every second until alls clear.
function checkLoadingState(callback) {
// if there's no open requests and no elements with ID/Class of loading, callback
if (window.openHTTPs < 1 && checkDomForNoLoading()) {
callback();
} else {
setTimeout(function () {
console.log('rechecking loading state')
checkLoadingState(callback);
}, 1000)
}
}
function callback() {
console.log('cb');
}
// Check DOM for elements with loading in class or id
function checkDomForNoLoading() {
console.log('checking dom for loading elements')
var ids = document.querySelector('[id*="loading"]');
var classes = document.querySelector('[class*="loading"]');
if (!ids && !classes) {
return true;
}
return false;
}
// Modify XMLHttpRequest.open method to update a global counter -> window.openHTTPs.
// Based on this SO post - https://stackoverflow.com/questions/9267451/how-to-check-if-http-requests-are-open-in-browser
(function (){
var oldOpen = XMLHttpRequest.prototype.open;
window.openHTTPs = 0;
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
window.openHTTPs++;
console.log(window.openHTTPs);
this.addEventListener("readystatechange", function() {
if(this.readyState == 4) {
window.openHTTPs--;
console.log(window.openHTTPs);
}
}, false);
oldOpen.call(this, method, url, async, user, pass);
}
})(XMLHttpRequest);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment