How to wait until an element exists?
You'll execute code when a DOM element emerges using MutationObserver
API. This efficient and lean method doesn't require jQuery or timers. Here's a crisp snippet that does the magic:
Keep reading for detailed explanations, alternative techniques, and fallback options.
Getter with the latest methods
Async/Await along promises
Let's turn the code into a promise which allows you to use await
within an async
function smoothly.
Backup with DOMNodeInserted
MutationObserver
not supported? No worries. This fallback to DOMNodeInserted
event helps out in case you are dealing with ancient browsers.
Though, DOMNodeInserted
might get too chatty and fire rapidly, so approach with caution.
Old school approaches
Interval based polling approach
If you like setInterval more than MutationObserver
, no problem. We can periodically check for the element's existence.
Beware, excessive checking or complex page structure might put a dent in your performance.
A timeout for the impatient
Imagine waiting indefinitely for an element that forgets to show up? Doesn't sound fun, right? Here's how we implement a timeout for that:
Save precious time with the inclusion of an appropriate timeout message.
Finishing up post-arrival
Once the element gets detected, to tie it in with the rest of your application flow, you might need to execute more functions or steps.
Transform your workflow to a busy line of factory workstations, where detection of the element signals it's time to start the next process.
Was this article helpful?