javascript tutorial - [Solved-5 Solutions] Pure javascript equivalent to jQuery’s $.ready() - javascript - java script - javascript array



Problem:

However, let's say We want to run a function that is written in standard JavaScript with no library backing it, and that We want to launch a function as soon as the page is ready to handle it. What's the proper way to approach this? We know We can do:

window.onload="myFunction()";
click below button to copy the code. By JavaScript tutorial team

We can use the body tag:

<body onload="myFunction()">
click below button to copy the code. By JavaScript tutorial team

...or We can even try at the bottom of the page after everything but the end body or html tag like:

<script type="text/javascript">
   myFunction();
</script>
click below button to copy the code. By JavaScript tutorial team

What is a cross-browser(old/new)-compliant method of issuing one or more functions in a manner like jQuery's $.ready()?

Solution 1:

The simplest thing to do in the absence of a framework that does all the cross-browser compatibility for we is to just put a call to our code at the end of the body. This is faster to execute than an onload handler because this waits only for the DOM to be ready, not for all images to load. And, this works in every browser.

<html>
<head>
</head>
<body>
Our HTML here

<script>
// self executing function here
(function() {
   // our page initialization code here
   // the DOM will be available here

})();
</script>
</body>
</html>
click below button to copy the code. By JavaScript tutorial team

If we really don't want to do it this way and we need cross browser compatibility and we don't want to wait for window.onload, then we probably should go look at how a framework like jQuery implements it's $(document).ready() method. It's fairly involved depending upon the capabilities of the browser. To give we a little idea what jQuery does (which will work wherever the script tag is placed). If supported, it tries the standard:

document.addEventListener('DOMContentLoaded', fn, false);
click below button to copy the code. By JavaScript tutorial team

with a fallback to:

window.addEventListener('load', fn, false )
click below button to copy the code. By JavaScript tutorial team

or for older versions of IE, it uses:

document.attachEvent("onreadystatechange", fn);
click below button to copy the code. By JavaScript tutorial team

with a fallback to:

window.attachEvent("onload", fn);
click below button to copy the code. By JavaScript tutorial team

And, there are some work-arounds in the IE code path that We don't quite follow, but it looks like it has something to do with frames. Here is a full substitute for jQuery's .ready() written in plain javascript:

(function(funcName, baseObj) {
    // The public function name defaults to window.docReady
    // but we can pass in our own object and own function name and those will be used
    // if we want to put them in a different namespace
    funcName = funcName || "docReady";
    baseObj = baseObj || window;
    var readyList = [];
    var readyFired = false;
    var readyEventHandlersInstalled = false;

    // call this when the document is ready
    // this function protects itself against being called more than once
    function ready() {
        if (!readyFired) {
            // this must be set to true before we start calling callbacks
            readyFired = true;
            for (var we = 0; we < readyList.length; i++) {
                // if a callback here happens to add new ready handlers,
                // the docReady() function will see that it already fired
                // and will schedule the callback to run right after
                // this event loop finishes so all handlers will still execute
                // in order and no new ones will be added to the readyList
                // while we are processing the list
                readyList[i].fn.call(window, readyList[i].ctx);
            }
            // allow any closures held by these functions to free
            readyList = [];
        }
    }

    function readyStateChange() {
        if ( document.readyState === "complete" ) {
            ready();
        }
    }

    // This is the one public interface
    // docReady(fn, context);
    // the context argument is optional - if present, it will be passed
    // as an argument to the callback
    baseObj[funcName] = function(callback, context) {
        if (typeof callback !== "function") {
            throw new TypeError("callback for docReady(fn) must be a function");
        }
        // if ready has already fired, then just schedule the callback
        // to fire asynchronously, but right away
        if (readyFired) {
            setTimeout(function() {callback(context);}, 1);
            return;
        } else {
            // add the function and context to the list
            readyList.push({fn: callback, ctx: context});
        }
        // if document already ready to go, schedule the ready function to run
        if (document.readyState === "complete") {
            setTimeout(ready, 1);
        } else if (!readyEventHandlersInstalled) {
            // otherwise if we don't have event handlers installed, install them
            if (document.addEventListener) {
                // first choice is DOMContentLoaded event
                document.addEventListener("DOMContentLoaded", ready, false);
                // backup is window load event
                window.addEventListener("load", ready, false);
            } else {
                // must be IE
                document.attachEvent("onreadystatechange", readyStateChange);
                window.attachEvent("onload", ready);
            }
            readyEventHandlersInstalled = true;
        }
    }
})("docReady", window);
click below button to copy the code. By JavaScript tutorial team

The latest version of the code is shared publicly on GitHub at Usage:

// pass a function reference
docReady(fn);

// use an anonymous function
docReady(function() {
    // code here
});

// pass a function reference and a context
// the context will be passed to the function as the first argument
docReady(fn, context);

// use an anonymous function with a context
docReady(function(context) {
    // code here that can use the context argument that was passed to docReady
}, ctx);
click below button to copy the code. By JavaScript tutorial team

This has been tested in:

IE6 and up
Firefox 3.6 and up
Chrome 14 and up
Safarwe 5.1 and up
Opera 11.6 and up
Multiple iOS devices
Multiple Android devices

Solution 2:

We would like to mention some of the possible ways here together with a pure javascript trick which works across all browsers:

// with jQuery 
$(document).ready(function(){ /* ... */ });

// shorter jQuery version 
$(function(){ /* ... */ });

// without jQuery (doesn't work in older IEs)
document.addEventListener('DOMContentLoaded', function(){ 
    // our code goes here
}, false);

// and here's the trick (works everywhere)
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
// use like
r(function(){
    alert('DOM Ready!');
});
click below button to copy the code. By JavaScript tutorial team

The trick here, as explained by the original author , is that we are checking the document.readyState property. If it contains the string in (as in uninitialized and loading, the first two DOM ready states out of 5) we set a timeout and check again. Otherwise, we execute the passed function.

Solution 3:

If we are doing VANILLA plain Javascript without jQuery, then we must use (IE9+)

document.addEventListener("DOMContentLoaded", function(event) { 
    //our code to run since DOM is loaded and ready
});
click below button to copy the code. By JavaScript tutorial team

Above is the equivalent of Jquery .ready:

$( document ).ready(function() {
    console.log( "ready!" );
});
click below button to copy the code. By JavaScript tutorial team

Which ALSO could be written SHORTHAND like this, which jQuery will run after the ready even occurs.

$(function() {
    console.log( "ready!" );
});
click below button to copy the code. By JavaScript tutorial team

NOT TO BE CONFUSED with BELOW (which is not meant to be DOM ready) DO NOT use an IFFWE like this that is self executing : example:

(function() {
   // our page initialization code here  - WRONG
   // the DOM will be available here   - WRONG
})();
click below button to copy the code. By JavaScript tutorial team

This IFFWE will NOT wait for our DOM to load. ( I'm even talking about latest version of Chrome browser!

Solution 4:

The good folks at HubSpot have a resource where we can find pure Javascript methodologies for achieving a lot of jQuery goodness - including ready

function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', fn);
  } else {
    document.attachEvent('onreadystatechange', function() {
      if (document.readyState != 'loading')
        fn();
    });
  }
}
click below button to copy the code. By JavaScript tutorial team

example inline usage:

ready(function() { alert('hello'); });
click below button to copy the code. By JavaScript tutorial team

Solution 5:

Our method (placing script before the closing body tag)

<script>
   myFunction()
</script>
</body>
</html>
click below button to copy the code. By JavaScript tutorial team

is a reliable way to support old and new browsers.


Related Searches to javascript tutorial - Pure javascript equivalent to jQuery’s $.ready()