开发者

Question about multiple ready()'s

开发者_运维问答Suppose I have:

<script src="script1.js"></script>
<script src="script2.js"></script>

Both of these scripts have ready() inside. Will the code in script2.js's ready() always execute after the first one?


Yes.

First of all, the code in script2.js will be executed after script1.js, as it comes later in the document (and the defer attribute is not set).

Furthermore, the implementation [source] of the ready function is:

ready: function( fn ) {
    // Attach the listeners
    jQuery.bindReady();

    // Add the callback
    readyList.done( fn );

    return this;
},

where readyList seems to be [source] a deferred object [docs]. That means the callbacks are executed in the order they have been added to that object.


jQuery uses its own Deferred object for this. The appropriate code of jQuery proves that it is executed in order:

When you call .ready, the function is added to the readyList:

readyList.done( fn );

When the DOM is ready, this function is executed:

readyList.resolveWith( document, [ jQuery ] );

The resolveWith function contains this code which executes the functions added as callbacks:

while( callbacks[ 0 ] ) {
    callbacks.shift().apply( context, args );
}

As you can see, the callback functions are shifted (popped out from the beginning of the callback array (i.e., readyList)), so the first gets executed before the second.


Multiple document ready(s) will be fired in order they are defind.


.ready() functions are called on first registered get first processed basis

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜