Created
March 10, 2025 13:36
-
-
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
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
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