Denis Ciccale’s version:
var DOMReady = function(a, b, c) {
b = document
c = 'addEventListener'
b[c] ? b[c]('DocumentContentLoaded', a) : window.attachEvent('onload', a)
}
DOMReady(function () {
alert('The DOM is Ready!');
});
Minimized:
var DOMReady = function(a,b,c){b=document,c='addEventListener';b[c]?b[c]('DOMContentLoaded',a):window.attachEvent('onload',a)}
Dustin Diaz’s version:
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
He also had a repo for it where the code is a bit different (and looks newer) so you might wanna try that, although I’ve found the above pretty effective as-is. His 0.3.0 branch is required for IE 6-7-8.
The native DOM function is:
document.addEventListener('DOMContentLoaded', function() {
});
In case you’re cool with only needing to support browsers that support that.
None of these should be use with the exception of Dustin Diaz’ version.
DOMContentLoaded
is an event that happens once, so if you attach a function after the event been fired, the function won’t be called — i.e. the site might break.This is especially an issue with asynchronously loaded scripts (
async
attribute or other methods)I use bloody-domready since it’s the only one that worked for me in a specific situation (auto-reload in IE10)
Great :D thanks
i’ve been using the following as a cross-browser dom ready solution and it’s as backwards compatible as anything else i’ve seen and shorter than the above (both excluding the Dustin Diaz version which is very nifty and now i wanna figure that one out):
document.onreadystatechange = function () { if (document.readyState == ‘complete’) { /* executes after dom is ready */ } };