Last active
November 24, 2022 18:49
-
-
Save opentechnologist/1a383136b63aca2f87ae08c3f3165eee to your computer and use it in GitHub Desktop.
a Promise-based class that resolves when DOM has finished loading.
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
/* | |
A simple Promise-based class that will resolve only after the DOM has completely loaded. | |
It can be used with or without a callback. But when a callback is supplied, the responsibility | |
of resolving or rejecting the Promise is passed on to the callback. | |
~Bu | |
*/ | |
class Deferred { | |
constructor(callback) { | |
const promise = new Promise((resolve, reject) => { | |
const executor = () => { | |
if (typeof callback === typeof (() => {})) { | |
callback(resolve, reject); | |
} else { | |
resolve(); | |
} | |
}; | |
const DOM_STATE_COMPLETE = 'complete'; | |
if (document.readyState === DOM_STATE_COMPLETE) { | |
executor(); | |
} else if (document.addEventListener) { | |
document.addEventListener('DOMContentLoaded', () => { | |
executor(); | |
}); | |
} else { | |
document.attachEvent('onreadystatechange', () => { | |
if (document.readyState === DOM_STATE_COMPLETE) { | |
executor(); | |
} | |
}); | |
} | |
}); | |
this.then = promise.then.bind(promise); | |
this.catch = promise.catch.bind(promise); | |
this.finally = promise.finally.bind(promise); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment