I needed a way to wait for an HTML element, matching a given CSS selector, to get added to the DOM.
waitForElement("#popup.annoying").then(el => {
el.remove();
});
I tried the usual approaches with MutationObserver
, polling, etc. - none of it responded quickly
enough, many of the existing solutions have performance issues, and a few of them don't actually
work for selectors like ul.foo > li.bar
if the foo
class gets added after the li.bar
elements
have already been added.
Then it hit me - the CSS engine is already doing this work using extremely sophisticated optimizations, why don't we just let the CSS engine do the work? Inject a "CSS animation", and wait for the "animation" to start. It's a rugged approach, no doubt - but it's simple, and fast.
On the "fast" part, I can't actually prove this - I have no idea how you'd even benchmark something like this. But the more common approaches, like searching the entire DOM in response to mutations or timers, definitely made my script noticeably slower.
Prior art:
- https://github.com/leodutra/waitforselector-js/blob/master/index.js
- https://github.com/lsphillips/WaitForTheElement/blob/master/src/wait-for-the-element.js
- https://github.com/azu/wait-for-element.js/blob/master/lib/wait-by-timer.js
- https://github.com/azu/wait-for-element.js/blob/master/lib/wait-by-observer.js
- https://github.com/tpkn/waitForSelector/blob/master/waitForSelector.js