2010-08-13 72 views
8

我知道在jQuery中对$(function(){})的调用是按照它们被定义的顺序执行的,但是我想知道是否可以控制队列的顺序?jQuery多文档就绪队列顺序

例如,是有可能的“Hello World 1”之前调用的“Hello World 2”:

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

的问题是,是否有可能......我已经知道它违背最佳实践;)

+0

为什么你会定义2个不同的$(函数(){}块我只用1把东西放在执行 – Gregg 2010-08-13 18:39:16

+0

的顺序是自上而下的@。 Gregg:考虑一下你在你的网站上使用第三方工具的情况,它利用了jQuery和document.ready进一步考虑你可能想要在你的页面上添加依赖于第三方文档的代码.ready在您之前先运行,并不总是容易控制或预测操作的顺序 – Mir 2012-03-08 18:04:34

回答

1

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

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(); 

你可以阅读更多关于它here

2

您可以使用jQuery的承诺来实现这样的事情。

下面是一个例子,其中jQuery.ready.promise帮助管理DOM就绪块的执行顺序:

  1. 在下面的例子中,第一DOM就绪块试图访问的高度测试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('<div style="background: #C00; height: 100px;" id="test-div"></div>'); 
    }); 
    

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

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