jQuery多文档就绪队列顺序问题

8

我知道在jQuery中,对于$(function(){ })进行的调用是按照它们定义的顺序执行的,但我想知道是否能够控制队列的顺序?

比如说,是否可以在调用"Hello World 1"之前先调用"Hello World 2":

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

问题是是否可能......我已经知道这违反了最佳实践 ;)

为什么要定义2个不同的$(function() { }块?我只会使用一个,并按照执行顺序自上而下放置事物。 - Gregg
@Gregg:考虑这样一种情况,你在你的网站上使用了一个使用jQuery和document.ready的第三方工具。进一步考虑,你可能希望在你的页面上添加依赖于第三方document.ready先运行的代码,然后才是你自己的代码。控制或预测操作的顺序并不总是容易的。 - Mir
4个回答

7
以下是如何进行操作的方法:
// 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();

您可以在此处了解更多相关的IT技术内容。


3

2
你可以使用jQuery Promise来实现类似的功能。
以下是一个示例,其中jQuery.ready.promise帮助管理DOM Ready块的执行顺序:
  1. In the following example, the first DOM Ready block is trying to access the height of the test div which is appended to the body in a later DOM Ready block. As in the Fiddle it fails to get it.

    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('<div style="background: #C00; height: 100px;" id="test-div"></div>');
    });
    

    Fiddle: http://jsfiddle.net/geektantra/qSHec/

  2. In the following example, it is doing exactly the same as the example before using jQuery.ready.promise. As in the Fiddle it works as required.

    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('<div style="background: #C00; height: 100px;" id="test-div"></div>');
    });
    

    Fiddle: http://jsfiddle.net/geektantra/48bRT/


1
这是可以做到的,但不容易。您需要对jQuery进行修改,可能要在此处进行操作。在jQuery开始调用循环内的这些函数之前,您需要添加代码来检查readyList数组并根据您的喜好重新排序元素。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接