johnny
johnny

Reputation: 1251

Why does jQuery fire the ready event asynchronously

In jQuery ready event logic:

// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
    // Handle it asynchronously to allow scripts the opportunity to delay ready
    return setTimeout( jQuery.ready, 1 );
}

Could you explain the comment: "Handle it asynchronously to allow scripts the opportunity to delay ready".

I don't understand what scripts and why to delay ready?

Upvotes: 5

Views: 345

Answers (2)

gdoron
gdoron

Reputation: 150253

If the ready callback(which fires the readyList) would have fire right away, you couldn't hold it's execution once the DOM is ready with the holdReady function.

jQuery.holdReady( hold )
Description: Holds or releases the execution of jQuery's ready event.

The $.holdReady() method allows the caller to delay jQuery's ready event.

This advanced feature would typically be used by dynamic script loaders that want to load additional JavaScript such as jQuery plugins before allowing the ready event to occur, even though the DOM may be ready.

This method must be called early in the document, such as in the immediately after the jQuery script tag. Calling this method after the ready event has already fired will have no effect.

Upvotes: 6

lbstr
lbstr

Reputation: 2832

it has to do with $.holdReady(), which allows you to delay the ready event. A use case might be that you want to do some initialization stuff before all of your other scripts run. You could delay ready until you are done initializing.

Upvotes: 0

Related Questions