Created
March 6, 2018 16:05
-
-
Save mattcodez/39cf97fe81afe8057c9c9510a4f04989 to your computer and use it in GitHub Desktop.
page loaded
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use only vanilla JS | |
function callWhenReadyToGo(cb) { | |
var allImagesLoaded = false; | |
// Look at all P and SPAN for very short text that says "loading" | |
// we don't want long text as it might be part of a longer paragraph then | |
var textEls = document.querySelectorAll('SPAN, P'); | |
var loadingEls = []; | |
for (var i = 0; i < textEls.lenth; i++){ | |
var el = textEls[i]; | |
if (el.innerText.match(/loading/i) && el.innerText.length < 20) { | |
loadingEls.push(el); | |
} | |
// after we find them, start polling their visability | |
var checkLoadingEls = function() { | |
if (allAreHidden(loadingEls)){ | |
//TODO: need to account for all loops to return | |
// if (!allImagesLoaded) { | |
// | |
// } | |
cb(); | |
return; | |
} | |
else { | |
setTimeout(checkLoadingEls, 500); | |
} | |
} | |
checkLoadingEls(); | |
} | |
var allImgs = document.querySelectorAll('IMG'); | |
// Look for spinners and indicator bars | |
for (var i = 0; i < allImgs.length; i++){ | |
var filename = img.src.substr(img.lastIndexOf('/')); | |
if (filename.match(/spinner/i) && filename.match(/.gif$/i)){ | |
likelyLoaders.push(img); | |
} | |
var checkSpinnerEls = function() { | |
if (allAreHidden(likelyLoaders)){ | |
cb(); | |
return; | |
} | |
else { | |
setTimeout(checkSpinnerEls, 500); | |
} | |
} | |
checkSpinnerEls(); | |
} | |
// are all the images loaded? | |
var likelyLoaders = []; | |
var notLoaded = 0; | |
for (var i = 0; i < allImgs.length; i++){ | |
var img = allImgs[i]; | |
if (!img.complete) { | |
notLoaded++; | |
img.onload = function(){if (--notLoaded === 0) allImagesLoaded = true;}; | |
img.onerror = function(){if (--notLoaded === 0) allImagesLoaded = true;}; | |
} | |
if (notLoaded === 0) { | |
allImagesLoaded = true; | |
return; | |
} | |
} | |
// Other possibilities: | |
// Hijack XHR requests | |
} | |
function allAreHidden(els){ | |
for (var i = 0; i < els.length; i++){ | |
var el = els[i]; | |
if (el.style.display !== 'none' && el.style.visibility === 'visible'){ | |
return false; | |
} else if (el.style.visibility !== 'hidden'){ | |
return false; | |
} | |
} | |
return true; | |
} | |
callWhenReadyToGo(function(){console.log('loaded!')}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment