Skip to content

Instantly share code, notes, and snippets.

@yckart
Forked from 140bytes/LICENSE.txt
Last active December 22, 2015 07:59
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 yckart/6441848 to your computer and use it in GitHub Desktop.
Save yckart/6441848 to your computer and use it in GitHub Desktop.
DOMReady
function a(
b // the callback function
) {
/p/.test(document.readyState) ? // if document's readyState is 'complete'
b() : // fire our callback-function
setTimeout(function () {
a(b) // otherwise do a delayed recursive function call
}, 10)
}
function a(b){/p/.test(document.readyState)?b():setTimeout(function(){a(b)}, 10)}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Yannick Albert <http://yckart.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "DOMReady",
"description": "Recursive document ready callback.",
"keywords": [
"dom",
"document",
"domready",
"ready",
"recursive"
]
}
<!DOCTYPE html>
<head>
<title>DOMReady</title>
<script>
var DOMReady = function a(b){/p/.test(document.readyState)?b():setTimeout(function(){a(b)}, 10)};
DOMReady(function () {
document.getElementById('ret').innerHTML = '140byt.es';
});
</script>
</head>
<body>
<div>Expected value: <b>140byt.es</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// better DOMReady ;)
</script>
</body>
@atk
Copy link

atk commented Sep 5, 2013

If you don't add a timeout value, this will be rather bad for the performance on some browsers. Also, you can use the parameter handover of settimeout to save the function body (In addition, regex check shamelessly ripped off https://github.com/dciccale/ki.js/blob/master/ki.js):

function a(b){/c/.test(document.readyState)?b():setTimeout(a,35,b)}

@yckart
Copy link
Author

yckart commented Sep 5, 2013

@atk Good point's! I'll merge the first one, however problem with your second suggestion is, that oldIE doesn't accept the third parameter in set-timeout/interval :( The regex part looks good though!

Update

The readyState could be 'loading', 'interactive', 'complete' (http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#documentreadystate), so we should test for 'm' or 'p' instead ;)

@atk
Copy link

atk commented Sep 6, 2013

"interactive" seems to be the phase when the DOM is already completely parsed and only sub-resources (images, async scripts) are loaded. Seems good enough for me for DOMready.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment