Cross-browser Document Ready with Vanilla JavaScript (IE8 included)

In need of a positive encouragment?

Go to Positivity By Ray Ray and grow a positive mindset! ❤️

In jQuery, developers are used to the $(document).ready(); function. This is just a check if your document is completely loaded, and all needed stuff is on your page. But since I left jQuery in my work, I wanted to have the same check but with Vanilla JavaScript.

So today I would love to share with you a snippet, that check’s if you DOM is ready without any dependencies!

Document Ready check

This snippet will covers all the browser to check if the DOM is ready.

    
        document.addEventListener("DOMContentLoaded", function() {
   console.log('Your document is ready!');
});
    

Document Ready check for IE8

Offcourse there is IE8, who wants a different way.

    
        document.attachEvent("onreadystatechange", function(){
 if (document.readyState === "complete"){
   console.log('Your document is ready!');
 }
});
    

Cross-browser Document Ready check

If I would create a small module of it, it would be like this:

    
        var domIsReady = (function(domIsReady) {
   var isBrowserIeOrNot = function() {
      return (!document.attachEvent || typeof document.attachEvent === "undefined" ? 'not-ie' : 'ie');
   }

   domIsReady = function(callback) {
      if(callback && typeof callback === 'function'){
         if(isBrowserIeOrNot() !== 'ie') {
            document.addEventListener("DOMContentLoaded", function() {
               return callback();
            });
         } else {
            document.attachEvent("onreadystatechange", function() {
               if(document.readyState === "complete") {
                  return callback();
               }
            });
         }
      } else {
         console.error('The callback is not a function!');
      }
   }

   return domIsReady;
})(domIsReady || {});
    

Source is on Gist and a demo is on Codepen.

And this is how you could use it:

    
        (function(document, window, domIsReady, undefined) {
   domIsReady(function() {
      console.log('My DOM is ready peeps!');
      document.querySelector('#page').style.background = 'blue';
   });
})(document, window, domIsReady);
    

 

Use a micro-library

You can also choose to use a small JavaScript Library if you like. It can be very usefull, but I prefer to intergrate the snippets above in my own code.

Hope this will help you build your website or application!