如何确保我的jQuery .ready最终运行

wcm*_*wcm 6 jquery asp.net-mvc-2

我有一个使用母版页的MVC 2 Web应用程序.在母版页中,有几个就绪块,就像下面散布在整个文件中的块一样

$(document).ready(function () {
   ...
});
Run Code Online (Sandbox Code Playgroud)

同样,我的许多观点也有分散的多个现成块.

我被要求将另一个准备好的块引入到最后运行的Master中.

我的问题是"有没有办法保证这个新的就绪块能够运行到最后?".我的想法是,如果我把它放在Master页面的最底部就能做到,但我似乎无法说服自己这是肯定的.

Ten*_*eff 5

这是jQuery的.add方法,用于将你$(document).ready()的回调推送到所有回调列表:

add = function( args ) {
    var i, length, elem, type, actual;
    for ( i = 0, length = args.length; i < length; i++ ) {
        elem = args[ i ];
        type = jQuery.type( elem );
        if ( type === "array" ) {
            // Inspect recursively
            add( elem );
        } else if ( type === "function" ) {
            // Add if not in unique mode and callback is not in
            if ( !flags.unique || !self.has( elem ) ) {
                list.push( elem );
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

来源:jQuery的回调

所以:它基本上做的是推动list数组内部的所有函数,并在事件被触发后 - 以相同的顺序调用它们,如果你的函数被推送到最后 - 它将被调用到最后.

要最后推送它,你可以在包含所有其他.js文件之后在头部声明它(只需确保$(document).ready()下面没有任何其他文件)