Cross-Browser Dependency-Free DOM Ready

Avatar of Chris Coyier
Chris Coyier on

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.