Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does jQuery's "document ready" function work?

Tags:

jquery

How is jQuery checking if the document is loaded? How it is checking that the document load is finished?

like image 291
Vasya Pupkin Avatar asked May 11 '11 04:05

Vasya Pupkin


People also ask

How does document ready function work?

The jQuery document ready function executes when the DOM (Document Object Model) is completely loaded in the browser. jQuery document ready is used to initialize jQuery/JavaScript code after the DOM is ready, and is used most times when working with jQuery. The Javascript/jQuery code inside the $(document).

What is the purpose of jQuery's document ready () handler?

The . ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate. This will often be a good time to perform tasks that are needed before the user views or interacts with the page, for example to add event handlers and initialize plugins.

What is difference between $( function () and document Ready?

So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.

Can I use document ready multiple times?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.


3 Answers

Check out the function bindReady in the source code.

They bind to the DOMContentLoaded event (or onreadystatechange on some browsers). They also have a fallback to the regular load event, in case the DOMContentLoaded isn't supported or not fired for other reasons. On browsers supporting it, they use this call:

document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

On IE <9:

document.attachEvent( "onreadystatechange", DOMContentLoaded);

The second instance of DOMContentLoaded in these calls is their own function - actually a reference to the ready function right above bindReady in the source code. This function will check that the DOM tree is actually done by checking for document.body. If it doesn't exist yet, they wait a millisecond (using setTimeout) and check again. When document.body exists, they traverse the list of callbacks you've set.

like image 80
Emil Vikström Avatar answered Oct 05 '22 15:10

Emil Vikström


So there is a little bit going on behind the scenes but this is the gist of it, directly for the jQuery source:

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

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", jQuery.ready, 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", DOMContentLoaded );

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

            // If IE and not a frame
            // continually check to see if the document is ready
            var toplevel = false;

            try {
                toplevel = window.frameElement == null;
            } catch(e) {}

            if ( document.documentElement.doScroll && toplevel ) {
                doScrollCheck();
            }
        }

So for most browsers (Mozilla, Opera and Webkit) there is a DOMContentLoaded event that jQuery is listening for, when that is triggered, then it calls all of the ready handlers you have registered with jQuery.

IE acts a little differently as they don't have the DOMContentLoaded event, they try hooking into the onreadystatechange event of the document, they also hook up the window.onload event, as well as do a sneaky bit of code where they continuously try and scroll the page every millisecond (doScrollCheck). Which ever one of these fires first triggers the ready handlers and the subsequent events are ignored.

I hope that makes sense and helps you out :)

like image 22
Alastair Pitts Avatar answered Oct 05 '22 15:10

Alastair Pitts


jQuery doesn't do anything that JavaScript cannot/does not do - it's simply a JavaScript framework/library. What it does is provide wrappers around JavaScript events that browsers implement, such as onload ($.load()) and DOMContentLoaded ($.ready()). Of course, there is a lot of work under the hood that attempts to make this behaviour as standard as possible across browsers and works around browser bugs, issues and incompatibilities.

For example, IE didn't really support DOMContentLoaded before IE 9 but jQuery has to provide an implementation for it. You might want to see these links to understand more about what this event is and how one might implement something similar, even without jQuery:

  • http://api.jquery.com/ready/#comment-85629494
  • http://www.zachleat.com/web/domcontentloaded-inconsistencies/
  • http://www.kryogenix.org/days/2007/09/26/shortloaded
  • $(document).ready equivalent without jQuery

If you really want to see what's being done by jQuery, you should check out the jQuery source.

like image 42
no.good.at.coding Avatar answered Oct 05 '22 17:10

no.good.at.coding