Javascript snippet to asynchronously detect when DOM is 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
class SampleApp() { | |
constructor () { | |
this.pageLoadingPromise = null; | |
} | |
waitForDomContentLoaded() { | |
if (!this.pageLoadingPromise) { | |
// this is the first time; prepare the promise | |
this.pageLoadingPromise = new Promise(resolve => { | |
// make sure that page is not already loaded (otherwise we'd listen forever) | |
if (document.readyState === 'loading') { | |
// document is still loading, so register listener | |
document.addEventListener("DOMContentLoaded", resolve); | |
} else { | |
// we are past loading, at least "interactive" level, and that's just what we need | |
resolve(); | |
} | |
}); | |
} | |
// subsequent calls are just going to return the original promise, be it fulfilled or not | |
return this.pageLoadingPromise; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment