Created
October 12, 2013 16:52
-
-
Save bloodyowl/6952252 to your computer and use it in GitHub Desktop.
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
/* | |
How to make a domReady function | |
*/ | |
;(function(win){ | |
var doc = win.document | |
/* | |
We'll use the document.readyState string | |
to define weather or not the dom is ready. | |
The RegExp matches all the states we can | |
act on. | |
*/ | |
, readyStateRegExp = /interactive|loaded|complete/ | |
/* | |
We need to store the callbacks that are | |
waiting for the document to be ready here. | |
*/ | |
, domReadyStack = [] | |
/* | |
Just a boolean not to repeat the test once | |
we've tested a positive state. | |
*/ | |
, isReady = false | |
/* | |
This method checks the document.readyState | |
string, and calls itself recursively as long | |
as necessary every 10ms. | |
*/ | |
function checkReadyState(){ | |
var item | |
if(readyStateRegExp.test(doc.readyState)) { | |
isReady = true | |
while(item = domReadyStack.shift()) { | |
/* | |
The main reason why to use setTimeout here | |
is that if an error is thrown within the | |
callback, we don't wan't the whole stack | |
to be stopped because the error has gained | |
the current | |
*/ | |
setTimeout(item, 0) | |
} | |
/* | |
Early return there, not to call the method | |
again. | |
*/ | |
return | |
} | |
setTimeout(checkReadyState, 10) | |
} | |
setTimeout(checkReadyState, 10) | |
function domReady(fn){ | |
if(typeof fn != "function") { | |
return | |
} | |
if(isReady) { | |
setTimeout(fn, 0) | |
return | |
} | |
domReadyStack.push(fn) | |
} | |
win.domReady = domReady | |
})(this.window) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment