I need to create a JavaScript Promise that will not resolve until a specific HTML element is loaded on the page.
I don't have any way of knowing when this element will be loaded, other than to simply poll the DOM for it.
It seems there should be a more concise way to accomplish this task. I don't want anything that's "clever" to the point of being difficult to understand, but I'm open to any feedback on this pattern.
The code must be ES5 compatible for the most part. Polyfills are probably ok, but it has to run on IE10+.
function getContainer() {
return new Promise(function (resolve, reject) {
waitForContainerElement(resolve);
});
}
function waitForContainerElement(resolve) {
var $configElement = $("#container");
if ($configElement.length === 0) {
setTimeout(waitForContainerElement.bind(this, resolve), 30);
} else {
resolve($configElement);
}
}
Usage:
getContainer.then(function($container){
...
});
I would normally implement a max poll time, but didn't want that to cloud the issue here.
meta
tag, but waiting for DOM ready is bullet-proof \$\endgroup\$