Cross-Browser Dependency-Free DOM Ready

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.

Comments

  1. User Avatar
    Federico Brigante
    Permalink to comment#

    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)

  2. User Avatar
    Anhvu
    Permalink to comment#

    Great :D thanks

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag