Skip to content

Instantly share code, notes, and snippets.

@opentechnologist
Created November 24, 2022 18:46
Show Gist options
  • Save opentechnologist/3a3f089d7f9be88cd0ef3b6002932e52 to your computer and use it in GitHub Desktop.
Save opentechnologist/3a3f089d7f9be88cd0ef3b6002932e52 to your computer and use it in GitHub Desktop.
a Promise-based class that resolves when DOM has finished loading.
/*
A simple Promise-based class that will resolve only after the DOM has completely loaded.
The callback's responsibility is to provide the value when the promise is fulfilled.
It can be used to return classes or objects created by code from deferred script tags.
~Bu
*/
class Deferred {
constructor(callback) {
const promise = new Promise((resolve, reject) => {
const DOM_STATE_COMPLETE = 'complete';
if (document.readyState === DOM_STATE_COMPLETE) {
resolve(callback());
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', () => {
resolve(callback());
});
} else {
document.attachEvent('onreadystatechange', () => {
if (document.readyState === DOM_STATE_COMPLETE) {
resolve(callback());
}
});
}
});
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