Create a gist now

Instantly share code, notes, and snippets.

@nutbread /on_ready.js Secret
Last active Nov 17, 2015

What would you like to do?
on_ready.js
/**
on_ready(callback)
Run a function as soon as the DOM of a webpage is ready.
The function may run immediately if the DOM is already ready.
@param callback
The function to run
*/
var on_ready = (function () {
// Vars
var callbacks = [],
check_interval = null,
check_interval_time = 250;
// Check if ready and run callbacks
var callback_check = function () {
if (
(document.readyState === "interactive" || document.readyState === "complete") &&
callbacks !== null
) {
// Run callbacks
var cbs = callbacks,
cb_count = cbs.length,
i;
// Clear callbacks, events, checking interval
callbacks = null;
window.removeEventListener("load", callback_check, false);
window.removeEventListener("DOMContentLoaded", callback_check, false);
document.removeEventListener("readystatechange", callback_check, false);
if (check_interval !== null) {
clearInterval(check_interval);
check_interval = null;
}
// Run callbacks
for (i = 0; i < cb_count; ++i) {
cbs[i].call(null);
}
// Okay
return true;
}
// Not executed
return false;
};
// Listen
window.addEventListener("load", callback_check, false);
window.addEventListener("DOMContentLoaded", callback_check, false);
document.addEventListener("readystatechange", callback_check, false);
// Callback adding function
return function (cb) {
if (callbacks === null) {
// Ready to execute
cb.call(null);
}
else {
// Delay
callbacks.push(cb);
// Set a check interval
if (check_interval === null && callback_check() !== true) {
check_interval = setInterval(callback_check, check_interval_time);
}
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment