JavaScript

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.

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

Explore available Java intern job opportunities in remote positions on Jooble

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.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button