trejder
trejder

Reputation: 17495

Is DOMContentLoaded event EXACTLY the same as jQuery's .ready() function?

I have replaced window.addEventListener('DOMContentLoaded', function() {}); with jQuery's $(document).bind('ready', function() {});, because first one failed to work on IE < 9 and I did not wanted to play with .attachEvent() for that dummy browser, if I could have this nicely covered by jQuery itself.

Shortly after replacement, I noticed that DOMContentLoaded event was always fired around 0-2 miliseconds after page load / refresh (at least this is what was logged by my logging script), while .ready() always requires at least 15-20 miliseconds, after page refresh, to be fired (again - as logged by script).

I'm asking purely for feeding my curiosity, why there is such "significant" delay? Of course, there is no problem for me, that jQuery is firing that event later. It is just, that because I want to know ALL the answers (and rule the world! :]), I can't sleep with that! :]

EDIT: in .ready() function doc some user (Nick (of Nexxar)) points out that: "jQuery simulates the non existing "DOMContentLoaded" event on IE, but the used mechanism fires much later than the event used on other browsers". Maybe this is the same, I'm asking for?

Upvotes: 41

Views: 42855

Answers (4)

SergO
SergO

Reputation: 2829

Does anybody still use jQuery except me? ;)

As of jQuery 3.0, only the $( handler ) syntax is recommended,
(which is equivalent to $( document ).ready( handler )).

From API docs: .ready()

Upvotes: 1

Simon_Weaver
Simon_Weaver

Reputation: 145950

Another reason for the 'ready' appearing to fire later (in practice) is that there may be many events hooked up to it. If any of these are long running synchronous operations then the ready event will come much later. For instance I use knockout.js and it can take 500ms to initialize the page.


However using your minimal test page that isn't the case of course. I tried running the following :

 console.log(window.performance.timing.domContentLoadedEventEnd -
             window.performance.timing.domContentLoadedEventStart);

This gives about 6ms even for your simple super page


Also I took your code and ran it through Chrome's performance tools and discovered a few interesting things:

enter image description here

  • BTW: The vertical blue bar is DOMCONTENTLOADED and the green is 'first paint'
  • You can see even just a super simple function call on the DOMCONTENTLOADED event can take 5ms (and this is on an i7). Remember it needs to be parsed and things need initializing.
  • The callbacks are shown in the cyan color (anonymous), the first is from the DOMCONTENTLOADED event and the second is the 'ready' callback.
  • You will notice 'Timer Fired' (i.e. setTimeout). So it is not instantaneous at by any means.

Looking at the jQuery source code you see they actually set a timer for the callbacks:

// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout( jQuery.ready );

I'm not exactly sure what they mean here (any idea) - but it explains the behavior. I could see it being helpful to avoid race conditions, and blocking the UI but 'delaying ready' is unclear to me.

Upvotes: 2

Esailija
Esailija

Reputation: 140220

Assuming browser that supports the event:

  1. The real event can support any document. jQuery will only use the document it was loaded in, no matter what you pass to it.
  2. jQuery will fire the event asynchronously even if the event has already happened. Attaching 'DOMContentLoaded' event will do nothing if the event has already happened.

There is no delay in these browsers, see http://jsfiddle.net/rqTAX/3/ (the offsets logged are in milliseconds).

For browsers that don't support the event, jQuery's will obviously work for them as well. It will use a hacky mechanism that is not the same as the real DOMContentLoaded and will not necessarily fire as soon as the real DOMContentLoaded would:

// The DOM ready check for Internet Explorer
function doScrollCheck() {
    if ( jQuery.isReady ) {
        return;
    }

    try {
        // If IE is used, use the trick by Diego Perini
        // http://javascript.nwbox.com/IEContentLoaded/
        document.documentElement.doScroll("left");
    } catch(e) {
        setTimeout( doScrollCheck, 1 );
        return;
    }

    // and execute any waiting functions
    jQuery.ready();
}

Upvotes: 27

ajm
ajm

Reputation: 20105

jQuery simulates this event by binding to the document's readystatechange event, which is the standard way of simulating DOMContentLoaded in oldIE.

According to the jQuery source, that event fires "late" but before window.onload. However, I can't find when that event fires exactly. DOMContentLoaded fires when the DOM is built and ready for scripting, so readystatechange fires after that; perhaps it waits for layout rendering or styling something like that, or the event is triggered later in the rendering/layout process?

Regardless, it will likely fire after DOMContentLoaded, likely due to when IE decides to update the document's readyState to "complete."

(If anyone has a definite answer, post a comment and I'll update this answer; I'd love to know when exactly it fires myself, and I can't find that answer in any documentation or on any sites I would expect like Quirksmode.)

Upvotes: 5

Related Questions