Skip to content

Instantly share code, notes, and snippets.

@gr1zix
Created March 10, 2025 13:36
Show Gist options
  • Save gr1zix/a8ac6cda92a08d71c18d496178b6fc86 to your computer and use it in GitHub Desktop.
Save gr1zix/a8ac6cda92a08d71c18d496178b6fc86 to your computer and use it in GitHub Desktop.
[JS Async DOM] Wait until async element will be added to the DOM then handle it
function waitForElement(selector, timeout = 5000) {
return new Promise((resolve, reject) => {
const startTime = Date.now();
function check() {
const element = document.querySelector(selector);
if (element) {
return resolve(element);
}
if (Date.now() - startTime >= timeout) {
return reject(new Error(`[Error] Element not found: ${selector}`));
}
setTimeout(check, 100);
}
check();
});
}
async function initVimeoPlayer(selector) {
try {
const iframe = await waitForElement(selector);
return new Vimeo.Player(iframe);
} catch (error) {
console.error(error);
return null;
}
}
// usage
if (playerType === "vimeo") {
initVimeoPlayer(iframeSelector).then(vimeoPlayer => {
if (vimeoPlayer) {
player = vimeoPlayer;
player.on("timeupdate", event => {
handleTimeUpdate(player, section, playerType, event.seconds);
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment