Skip to content

Instantly share code, notes, and snippets.

@Rayraegah
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rayraegah/ada78f3876d542feb8f2 to your computer and use it in GitHub Desktop.
Save Rayraegah/ada78f3876d542feb8f2 to your computer and use it in GitHub Desktop.
senpai will notice me
/**
* senpai.js v1.0.1
* @description A document ready state event handler and dispatcher.
* @author Rayraegah Ownsu
* @usage bodyIsReady(fn); || bodyIsReady(function () {...}); || bodyIsReady(fn, args); || bodyIsReady(function (args) {...}, ctx);
*
* ===========
* Change log:
* ===========
* v1.0.1
* - Added comments to save lives
* - Removed explicit variable names
* - refrence to meme used in variable names
*/
/*! #include meme "I Hope Senpai Will Notice Me" && "My Body is Ready". */
(function(senpai, club) {
senpai = senpai || "bodyIsReady";
club = club || window;
var harem = [];
var noticed = false;
var beingNoticedBySenpai = false;
// call this when your body is ready
// this function protects itself, i.e. senpai will only notice you once
function notice() {
if (!noticed) {
// this must be set to true before we start calling callbacks
noticed = true;
for (var i = 0; i < harem.length; i++) {
harem[i].fn.call(window, harem[i].ctx);
}
// allow any closures held by these functions to free
harem = [];
}
}
function myBodyisReady() {
if ( document.readyState === "complete" ) {
notice();
}
}
club[senpai] = function(callback, context) {
// to fire asynchronously, but right away
if (noticed) {
setTimeout(function() {callback(context);}, 1);
return;
} else {
// add the function and context to the list
harem.push({fn: callback, ctx: context});
}
if (document.readyState === "complete") {
setTimeout(notice, 1);
} else if (!beingNoticedBySenpai) {
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", notice, false);
// backup is window load event
window.addEventListener("load", notice, false);
} else {
// must be IE
document.attachEvent("onreadystatechange", myBodyisReady);
window.attachEvent("onload", notice);
}
beingNoticedBySenpai = true;
}
};
})("bodyIsReady", window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment