Home » JavaScript » JavaScript Document Ready Example

About Era Balliu

Era Balliu
Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.

JavaScript Document Ready Example

“Document ready” is a technique widely used by everyone who uses JavaScript or jQuery in their code, yet only a few people know exactly why it is used. Primarily, it is used to make sure that all your external scripts are loaded properly.

Other reasons to use it are for having unobtrusive JavaScript and separation of concerns. Another perk is the protection it provides against browser bugs in case you make a mistake. Is it necessary? No, it is not. But it is good programming practice to use it.

JavaScript Interview Coming Up?

Subscribe to our newsletter and download the Ultimate JavaScript interview questions and answers collection right now!

In order to get you prepared for your next JavaScript interview, we have compiled a huge list of relevant questions and their respective answers. Besides studying them online you may download the eBook in PDF format!

 

Pure JavaScript document ready

First we create an immediately invoked function expression so that we can have non-public state variables, and we do it like this:

(function(funcName, baseObj) {
//content here
})("docReady", window);

Note: Every snippet of code in the following part goes inside the curly brackets, where now is written //content here.

Later we set the function name to docReady and the base object to object.These can be set to the object and function name you want, and be used in a different namespace. It goes like this:

 funcName = funcName || "docReady";
    baseObj = baseObj || window;
    var readyList = [];
    var readyFired = false;
    var readyEventHandlersInstalled = false;

When the document is ready we call the ready() function,like this:

    function ready() {
        if (!readyFired) {
            readyFired = true;
            for (var i = 0; i < readyList.length; i++) {
                readyList[i].fn.call(window, readyList[i].ctx);
            }
            readyList = [];
        }
    }

Before we start calling callbacks we should give the value true to readyFired. If by any chance, callbacks happen to add new ready handlers, the docReady() function will see that it already fired and will schedule this callback right after the for loop finishes it’s execution. This way all handlers are executed in their order and we can be sure that no new ones will be added to the readyList while it is still being executed. Then, we free all closures held by these functions by setting the readyList to an empty array.

The ready() function protects itself against being called more than once.

Now we place the code for the interface. It goes like this:

 baseObj[funcName] = function(callback, context) {
        //content
    }

The context argument is optional, and if included, it will go as an argument to the callback. But what’s instead of the //content? Here you go.

Take a look at this code, which will go in the place of //content, written in the code above:

        if (readyFired) {
            setTimeout(function() {callback(context);}, 1);
            return;
        } else {
            readyList.push({fn: callback, ctx: context});
        }

We have a conditional with the condition that if readyFired has fired already, to schedule the callback to execute immediately, though asynchronously. If not, add it to the list, so it can be executed in order.

We check to see if the document.readystate === "complete" and if so, we have to schedule the ready() function to run. If we don’t have the ready event handlers installed, we install them right away. If document.addEventListener exists, then install event handlers using .addEventListener() for both "DOMContentLoaded" and "load" events. The "load" event is optional, as it is used only for backup. Otherwise, if document.addEventListener doesn’t exist, then install event handlers using .attachEvent() for "onreadystatechange" and "onload" events.

        if (document.readyState === "complete") {
            setTimeout(ready, 1);
        } else if (!readyEventHandlersInstalled) {
            if (document.addEventListener) {
                document.addEventListener("DOMContentLoaded", ready, false);
                window.addEventListener("load", ready, false);
            } else {
                document.attachEvent("onreadystatechange", readyStateChange);
                window.attachEvent("onload", ready);
            }
            readyEventHandlersInstalled = true;
        }

And with this, we’re set. Can we do it differently? Of course.

Document Ready using JQuery

If you want to use jQuery to detect whether your document is ready or not, you have two main functions: $(document).ready() and $( window ).load(function() { ... }). Let’s introduce them one by one.

The $(document).ready() will be run once, after the DOM is already loaded. This is how the code goes:

$( document ).ready(function() {
    console.log( "ready!" );
});

You can present this same function differently, by passing another function instead of the anonymous one. First you have to write the function and then use it by the $(document).ready() method. The code would look like this:

function otherFunction( jQuery ) {
    // Code to run when the document is ready.
}
 $( document ).ready( otherFunction );

The $( window ).load(function() { ... }) function is executed only after the DOM and all the images or videos of the website are loaded. It is used in the same way as $( document ).ready();. Here’s how it will look:

$( window ).load(function() {
        console.log( "window loaded" );
 });

With that, we are now able to detect whether our document is ready or not. Use whatever is more convenient for you, be it plain JavaScript or JQuery.

Download the source code

This was an example of document ready using JavaScript.

Download
You can download the full source code of this example here: DocumentReady

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook

 

and many more ....

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Want to take your WEB dev skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • PHP Programming Cookbook
  • jQuery Programming Cookbook
  • Bootstrap Programming Cookbook
  • Building WEB Apps with Node.js
  • CSS Programming Cookbook
  • HTML5 Programming Cookbook
  • AngularJS Programming Cookbook