Skip to content

Instantly share code, notes, and snippets.

@raglan-road
Created September 28, 2012 15:32
Show Gist options
  • Save raglan-road/3800546 to your computer and use it in GitHub Desktop.
Save raglan-road/3800546 to your computer and use it in GitHub Desktop.
Promised-based poll for element's availability in the DOM
// Poll until an element is "available" in the DOM, returning a promise that resolves when the element is in the DOM and scriptable.
$.available = function (id) {
var _poll = function(id, dfd) {
if(document.getElementById(id)) {
dfd.resolve(document.getElementById(id));
}
else {
setTimeout(function() {
_poll(id, dfd);
}, 100);
}
};
return $.Deferred(function(dfd) {
_poll(id, dfd);
}).promise();
}
// Usage: $.available('foo').done(function(){ // do something that depends on div#foo being available })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment