Skip to content

Instantly share code, notes, and snippets.

@elliotboney
Last active August 29, 2015 14:02
Show Gist options
  • Save elliotboney/4d90c24f6be375038c44 to your computer and use it in GitHub Desktop.
Save elliotboney/4d90c24f6be375038c44 to your computer and use it in GitHub Desktop.
Wait until ready w/javascript
$.fn.onAvailable = function(fn) {
var sel = this.selector;
var timer;
if (this.length > 0) {
fn.call(this);
} else {
timer = setInterval(function() {
if ($(sel).length > 0) {
fn.call($(sel));
clearInterval(timer);
}
}, 100);
}
};
(function(window, document) {
/** Milliseconds between retries */
var POLL_INTERVAL = 20;
/** Number of attempts to locate element */
var POLL_RETRIES = 2000;
function onLoad(callback) {
if (document.readyState === "complete") {
setTimeout(callback, 1);
} else if (document.addEventListener) {
window.addEventListener("load", callback, false);
} else {
window.attachEvent("onload", callback);
}
}
var isReady = false;
onLoad(function() {
isReady = true;
});
var interval = null,
listeners = [],
pollRetries;
/**
* Polls the DOM for an element matching the supplied id and fires the
* associated callback method
*/
function checkAvailable() {
var i, l, listener, el, missed = 0;
for (i = 0, l = listeners.length; i < l; i++) {
listener = listeners[i];
if (listener) {
el = document.getElementById(listener.id);
/**
* If the DOM element is found, execute callbacks for all related
* onAvailable listeners. If the DOM is ready or the next sibling
* is detected, execute callbacks for all onContentReady listeners.
*/
if (el && (!listener.checkContent || (listener.checkContent && (el.nextSibling || el.parentNode.nextSibling || isReady)))) {
try {
listener.callback.call(el, listener.obj);
} catch (ex) {
console.log(ex);
}
listeners[i] = null;
} else {
missed++;
}
}
}
pollRetries--;
if (missed === 0 || pollRetries <= 0) {
interval = window.clearInterval(interval);
if (listeners.length) {
listeners.splice(0, listeners.length);
}
}
listener = el = null;
}
function onAvailable(id, callback, obj, checkContent) {
pollRetries = POLL_RETRIES;
listeners.push({
id: id,
callback: callback,
obj: obj,
checkContent: !! checkContent
});
if (!interval) {
interval = window.setInterval(checkAvailable, POLL_INTERVAL);
}
}
window.onAvailable = onAvailable;
}(window, document));
(function() {
if (typeof whatever !== 'undefined') {
// do stuff with 'whatever'
} else {
// Keep checking until mmenu can launch
setTimeout(arguments.callee, 50); //change this time
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment