javascript - without - jquery document ready equivalent

$(document).ready equivalent without jQuery (20)

Cross-browser (old browsers too) and a simple solution:

var docLoaded = setInterval(function () {
    if(document.readyState !== "complete") return;

        Your code goes here i.e. init()
}, 30);

Showing alert in jsfiddle

I have a script that uses $(document).ready, but it doesn't use anything else from jQuery. I'd like to lighten it up by removing the jQuery dependency.

How can I implement my own $(document).ready functionality without using jQuery? I know that using window.onload will not be the same, as window.onload fires after all images, frames, etc. have been loaded.

Edit of the edit of @duskwuff to support Internet Explorer 8 too. The difference is a new call to the function test of the regex and the setTimeout with an anonymous function.

Also, I set the timeout to 99.

function ready(f){/in/.test(document.readyState)?setTimeout(function(){ready(f);},99):f();}

For IE9+:

function ready(fn) {
  if (document.readyState != 'loading'){
  } else {
    document.addEventListener('DOMContentLoaded', fn);

Here is the smallest code snippet to test DOM ready which works across all browsers (even IE 8):

    alert('DOM Ready!');
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

See this answer.

How about this solution?

// other onload attached earlier
window.onload=function() {

tmpPreviousFunction=window.onload ? window.onload : null;

// our onload function
window.onload=function() {
   alert('another message');

   // execute previous one
   if (tmpPreviousFunction) tmpPreviousFunction();

I simply use:

    //reference/manipulate DOM here

And unlike document.addEventListener("DOMContentLoaded" //etc as in the very top answer, it works as far back as IE9 -- only indicates as recently as IE11.

For instance, go to, choose Internet Explorer 9 from the dropdown, enter and click "Render", and you will see something akin to the screenshot at the bottom of this post.

See the following Javascript code I am using in the header to manipulate the style of the Jekyll "hacker" theme to my liking -- in particular you can reference the if (location.pathname !== rootPath) block to see how I am inserting the Home and Blog Home links, which are being displayed by IE9 per the NetRenderer site.

Interestingly I stumbled upon this setTimeout solution in 2009: Is checking for the readiness of the DOM overkill?, which probably could have been worded slightly better, as I meant by using various frameworks' more complicated approaches.

setTimeout(function() {//delay execution until after dom is parsed
    var containerEls = document.getElementsByClassName('container');
    var headingEl = containerEls[0].getElementsByTagName('h1')[0];
    var headerEl = document.getElementsByTagName('header')[0];
    var downloadsSectionEl = document.getElementById('downloads');
    var rootPath = "/";
    var blogRootPath = "/blog/";

    containerEls[0].style.maxWidth = '800px';
    containerEls[1].style.maxWidth = '800px'; = '0'; = '7px'; = '0';

    if (location.pathname !== rootPath) {
        downloadsSectionEl.appendChild(generateNavLink('Home', rootPath));
        if (location.pathname !== blogRootPath) {
            downloadsSectionEl.appendChild(document.createTextNode(' | '));
            downloadsSectionEl.appendChild(generateNavLink('Blog Home', blogRootPath));

    function generateNavLink(linkText, hrefPath) {
        var navLink = document.createElement('a');
        var linkTextNode = document.createTextNode(linkText);
        navLink.setAttribute('href', hrefPath);
        return navLink;

I was recently using this for a mobile site. This is John Resig's simplified version from "Pro JavaScript Techniques". It depends on addEvent.

var ready = ( function () {
  function ready( f ) {
    if( ready.done ) return f();

    if( ready.timer ) {
    } else {
      addEvent( window, "load", isDOMReady );
      ready.ready = [ f ];
      ready.timer = setInterval(isDOMReady, 13);

  function isDOMReady() {
    if( ready.done ) return false;

    if( document && document.getElementsByTagName && document.getElementById && document.body ) {
      clearInterval( ready.timer );
      ready.timer = null;
      for( var i = 0; i < ready.ready.length; i++ ) {
      ready.ready = null;
      ready.done = true;

  return ready;

If you are loading jQuery near the bottom of BODY, but are having trouble with code that writes out jQuery(<func>) or jQuery(document).ready(<func>), check out jqShim on Github.

Rather than recreate its own document ready function, it simply holds onto the functions until jQuery is available then proceeds with jQuery as expected. The point of moving jQuery to the bottom of body is to speed up page load, and you can still accomplish it by inlining the jqShim.min.js in the head of your template.

I ended up writing this code to make moving all the scripts in WordPress to the footer, and just this shim code now sits directly in the header.

It is worth looking in Rock Solid addEvent() and

Here is the code in case the site goes down

function addEvent(obj, type, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(type, fn, false);
        EventCache.add(obj, type, fn);
    else if (obj.attachEvent) {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
        obj.attachEvent( "on"+type, obj[type+fn] );
        EventCache.add(obj, type, fn);
    else {
        obj["on"+type] = obj["e"+type+fn];

var EventCache = function(){
    var listEvents = [];
    return {
        listEvents : listEvents,
        add : function(node, sEventName, fHandler){
        flush : function(){
            var i, item;
            for(i = listEvents.length - 1; i >= 0; i = i - 1){
                item = listEvents[i];
                    item[0].removeEventListener(item[1], item[2], item[3]);
                if(item[1].substring(0, 2) != "on"){
                    item[1] = "on" + item[1];
                    item[0].detachEvent(item[1], item[2]);
                item[0][item[1]] = null;

// Usage
addEvent(window, 'unload', EventCache.flush);
addEvent(window, 'load', function(){alert("I'm ready");});

It's always good to use JavaScript equivalents as compared to jQuery. One reason is one fewer library to depend on and they are much faster than the jQuery equivalents.

One fantastic reference for jQuery equivalents is

As far as your question is concerned, I took the below code from the above link :) Only caveat is it only works with Internet Explorer 9 and later.

function ready(fn) {
    if (document.readyState != 'loading') {
    else {
        document.addEventListener('DOMContentLoaded', fn);

Place your <script>/*JavaScript code*/</script> right before the closing </body> tag.

Admittedly, this might not suit everyone's purposes since it requires changing the HTML file rather than just doing something in the JavaScript file a la document.ready, but still...

Poor man's solution:

var checkLoad = function() {   
    document.readyState !== "complete" ? setTimeout(checkLoad, 11) : alert("loaded!");   


View Fiddle

Added this one, a bit better I guess, own scope, and non recursive

    var tId = setInterval(function() {
        if (document.readyState == "complete") onComplete()
    }, 11);
    function onComplete(){

View Fiddle

The jQuery answer was pretty useful to me. With a little refactory it fitted my needs well. I hope it helps anybody else.

function onReady ( callback ){
    var addListener = document.addEventListener || document.attachEvent,
        removeListener =  document.removeEventListener || document.detachEvent
        eventName = document.addEventListener ? "DOMContentLoaded" : "onreadystatechange", eventName, function(){
        removeListener( eventName, arguments.callee, false )
    }, false )

The ready function in jQuery does a number of things. Frankly, I don't see that point of replacing it unless you have amazingly small output from your website. jQuery is a pretty tiny library, and it handles all sorts of cross-browser things you'll need later.

Anyway, there's little point in posting it here, just open up jQuery and look at the bindReady method.

It starts by calling either document.addEventListener("DOMContentLoaded") or document.attachEvent('onreadystatechange') depending on the event model, and goes on from there.

There is a standards based replacement,DOMContentLoaded that is supported by over 98% of browsers, though not IE8:

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work

jQuery's native function is much more complicated than just window.onload, as depicted below.

function bindReady(){
    if ( readyBound ) return;
    readyBound = true;

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {
        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){
            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
        }, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {
        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );

        // If IE and not an iframe
        // continually check to see if the document is ready
        if ( document.documentElement.doScroll && window == ) (function(){
            if ( jQuery.isReady ) return;

            try {
                // If IE is used, use the trick by Diego Perini
            } catch( error ) {
                setTimeout( arguments.callee, 0 );

            // and execute any waiting functions

    // A fallback to window.onload, that will always work
    jQuery.event.add( window, "load", jQuery.ready );

This approach is the shortest way I can think of.

The solution based on the DOMContentLoaded event only works if the script is loaded before the document, whereas the lazy check suggested here ensures the code is executed always, even in scripts loaded dynamically later on, exactly as the JQuery's document ready.

This code is compatible with all browsers (including some legacy, down to IE6 and Safari for Windows).

(function ready() {
    if (!document.body) {setTimeout(ready, 50); return;}
    // Document is ready here

This question was asked quite a long time ago. For anyone just seeing this question, there is now a site called "you might not need jquery" which breaks down - by level of IE support required - all the functionality of jquery and provides some alternative, smaller libraries.

IE8 document ready script according to you might not need jquery

function ready(fn) {
    if (document.readyState != 'loading')
    else if (document.addEventListener)
        document.addEventListener('DOMContentLoaded', fn);
        document.attachEvent('onreadystatechange', function() {
            if (document.readyState != 'loading')

This was a good https://.com/a/11810957/185565 poor man's solution. One comment considered a counter to bail out in case of emergency. This is my modification.

function doTheMagic(counter) {
  alert("It worked on " + counter);

// wait for document ready then call handler function
var checkLoad = function(counter) {
  if (document.readyState != "complete" && counter<1000) {
    var fn = function() { checkLoad(counter); };
  } else doTheMagic(counter);

Try this:

function ready(callback){
    if(typeof callback === "function"){
        document.addEventListener("DOMContentLoaded", callback);
        window.addEventListener("load", callback);
        throw new Error("Sorry, I can not run this!");
    console.log("It worked!");

We found a quick-and-dirty cross browser implementation of ours that may do the trick for most simple cases with a minimal implementation:

window.onReady = function onReady(fn){
    document.body ? fn() : setTimeout(function(){ onReady(fn);},50);