-
-
Save nutbread/db273ef22203755184c5 to your computer and use it in GitHub Desktop.
on_ready.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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