jQuery多文档就绪队列顺序

我知道jQuery中对$(function(){})的调用是按照定义的顺序执行的,但是我想知道你是否可以控制队列的顺序?

例如,是否可以在“Hello World 1”之前调用“Hello World 2”:

$(function(){ alert('Hello World 1') }); $(function(){ alert('Hello World 2') }); 

问题是它是否可能……我已经知道它违背了最佳做法;)

这些函数被添加到私有数组readyList ,所以我说它不能被操作。

http://github.com/jquery/jquery/blob/master/src/core.js#L47

这是你将如何去做:

 // lower priority value means function should be called first var method_queue = new Array(); method_queue.push({ method : function() { alert('Hello World 1'); }, priority : 2 }); method_queue.push({ method : function() { alert('Hello World 2'); }, priority : 1 }); function sort_queue(a, b) { if( a.priority < b.priority ) return -1; else if( a.priority == b.priority ) return 0; else return 1; } function execute_queue() { method_queue.sort( sort_queue ); for( var i in method_queue ) method_queue[i].call( null ); } // now all you have to do is execute_queue(); 

你可以在这里阅读更多相关信息

您可以使用jQuery promise来实现这样的function。

以下是jQuery.ready.promise帮助管理DOM Ready Blocks执行顺序的示例:

  1. 在下面的示例中,第一个DOM Ready块正在尝试访问测试div的高度,该高度附加到后面的DOM Ready块中的主体。 就像在小提琴中一样,它无法得到它。

     jQuery(function () { var testDivHeight = jQuery("#test-div").outerHeight(); if(testDivHeight) { alert("Height of test div is: "+testDivHeight); } else { alert("Sorry I cannot get the height of test div!"); } }); jQuery(function () { jQuery('body').append('
    '); });

    小提琴: http : //jsfiddle.net/geektantra/qSHec/

  2. 在下面的示例中,它与使用jQuery.ready.promise之前的示例完全相同。 就像在小提琴中一样,它可以按要求工作。

     jQuery(function () { jQuery.ready.promise().done(function () { var testDivHeight = jQuery("#test-div").outerHeight(); if(testDivHeight) { alert("Height of test div is: "+testDivHeight); } else { alert("Sorry I cannot get the height of test div!"); } }); }); jQuery(function () { jQuery('body').append('
    '); });

    小提琴: http : //jsfiddle.net/geektantra/48bRT/

它可以做到,但不容易。 你可能必须破解jQuery本身,可能在这里 。 在jQuery开始在while循环中调用这些函数之前,您必须添加代码来检查readyList数组并根据您的偏好重新排序元素。