Skip to content

Instantly share code, notes, and snippets.

@luciopaiva
Last active July 24, 2017 02:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luciopaiva/51968fd7890c565b3f49a1f2a7136c41 to your computer and use it in GitHub Desktop.
Save luciopaiva/51968fd7890c565b3f49a1f2a7136c41 to your computer and use it in GitHub Desktop.
Javascript snippet to asynchronously detect when DOM is loaded
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