Skip to content

Instantly share code, notes, and snippets.

@mutoo
Created May 21, 2013 02:16
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 mutoo/5617115 to your computer and use it in GitHub Desktop.
Save mutoo/5617115 to your computer and use it in GitHub Desktop.
compatible domReady
// initialize when DOM content is loaded
var domReady = function() {
var fns = [];
var init = function() {
if (!arguments.callee.done) { // run init functions once
arguments.callee.done = true;
for (var i = 0; i < fns.length; i++) {
fns[i]();
}
}
};
// listeners for different browsers
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, false);
}
if (ua.ie) {
(function() {
try {
// throws errors until after ondocumentready
document.documentElement.doScroll('left');
} catch (e) {
setTimeout(arguments.callee, 50);
return;
}
// no errors, fire
init();
})();
// trying to always fire before onload
document.onreadystatechange = function() {
if (document.readyState === 'complete') {
document.onreadystatechange = null;
init();
}
};
}
if (ua.webkit && document.readyState) {
(function() {
if (document.readyState !== 'loading') {
init();
} else {
setTimeout(arguments.callee, 10);
}
})();
}
window.onload = init; // fallback
return function(fn) { // add fn to init functions
if (typeof fn === 'function') {
fns[fns.length] = fn;
}
return fn;
};
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment