Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
// 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