Skip to content

Instantly share code, notes, and snippets.

@stevenslack
Created April 20, 2022 12:07
Show Gist options
  • Save stevenslack/cb5d807fe74a72ead75a577b2466f545 to your computer and use it in GitHub Desktop.
Save stevenslack/cb5d807fe74a72ead75a577b2466f545 to your computer and use it in GitHub Desktop.
Check for dependencies concurrently while the page loads.
// Set the window object to be set at a later time then the promise resolve.
setTimeout(() => {
window.DEP = 'I am here!';
}, 31000)
async function dependencyReady() {
// Set a timeout limit of 30 seconds.
const time = Date.now() + 30000;
// Runs an until time is past and window.DEP is ready.
while (!Object.prototype.hasOwnProperty.call(window, 'DEP')) {
try {
await new Promise((resolve, reject) => {
setTimeout(resolve, 100);
if (time < Date.now()) {
// Reject the promise if our timeout limit of 30 seconds is reached.
reject('Timeout error. window.DEP is undefined');
}
});
} catch (e) {
// Break the loop and display a console error.
console.error(e);
break;
}
}
};
// Check the existence of the dependency.
dependencyReady().then(() => {
console.log(window.DEP);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment