Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Created February 17, 2018 14:57
Show Gist options
  • Save ernestlv/abefd8c5f686e2c9060494767521292b to your computer and use it in GitHub Desktop.
Save ernestlv/abefd8c5f686e2c9060494767521292b to your computer and use it in GitHub Desktop.
Problem is to wait for all ajax calls to finish loading DOM. We count # of DOM elements and wait X secs if DOM changes page still loading. Adjust sec param for different websites
function callWhenReady(callBack, sec) {
var wait4Loop = ( sec || 5 ) * 4;
var loopNum = 0;
var domCount = document.querySelectorAll('*').length; //count DOM elements
var i = setInterval(function(){ // after 1/4 of a sec
var newCount = document.querySelectorAll('*').length; //count DOM elements
if (domCount != newCount){ // new DOM elements are counted, page still loading
domCount = newCount;
loopNum = 0;
}else{ // wait X sec if node count does not change, page likely finished loading.
loopNum++;
if (loopNum === wait4Loop){
clearInterval(i);
callBack();
}
}
}, 250);
}
callWhenReady(function(){ alert("DOM is ready !!!")})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment