Last active
August 29, 2015 14:10
-
-
Save Rayraegah/ada78f3876d542feb8f2 to your computer and use it in GitHub Desktop.
senpai will notice me
This file contains hidden or 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
/** | |
* 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