jQuery 多文档就绪队列顺序
我知道 jQuery 中对 $(function(){ }) 的调用是按照定义的顺序执行的,但我想知道您是否可以控制队列的顺序?
例如,是否可以在“Hello World 1”之前调用“Hello World 2”:
$(function(){ alert('Hello World 1') });
$(function(){ alert('Hello World 2') });
问题是是否可能......我已经知道这违背了最佳实践;)
I know calls to $(function(){ }) in jQuery are executed in the order that they are defined, but I'm wondering if you can control the order of the queue?
For example, is it possible to call "Hello World 2" before "Hello World 1":
$(function(){ alert('Hello World 1') });
$(function(){ alert('Hello World 2') });
The question is whether or not it's possible... I already know it goes against best practice ;)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下是您的操作方法:
您可以阅读更多相关信息 这里
here is how you would go about doing it:
You can read more about it here
这些函数被添加到私有数组
readyList
中,因此我认为它无法进行操作。http://github.com/jquery/jquery/blob/ master/src/core.js#L47
Those functions are added to a private array
readyList
, so I'd say it isn't accessible for manipulation.http://github.com/jquery/jquery/blob/master/src/core.js#L47
你可以使用 jQuery Promise 来实现这样的事情。
以下是 jQuery.ready.promise 帮助管理 DOM Ready 块的执行顺序的示例:
在以下示例中,第一个 DOM Ready 块尝试访问附加到主体的测试 div 的高度在稍后的 DOM Ready 块中。就像在小提琴中一样,它无法获取它。
小提琴:http://jsfiddle.net/geektantra/qSHec/
在以下示例中,它与使用 jQuery.ready.promise 之前的示例完全相同。就像在 Fiddle 中一样,它按要求工作。
小提琴:http://jsfiddle.net/geektantra/48bRT/
You can use jQuery promise to achieve something like this.
Following is an example where jQuery.ready.promise helps managing the order of execution of DOM Ready Blocks:
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.
Fiddle: http://jsfiddle.net/geektantra/qSHec/
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.
Fiddle: http://jsfiddle.net/geektantra/48bRT/
这是可以做到的,但并不容易。你必须破解 jQuery 本身,可能是这里。在 jQuery 开始在
while
循环内调用这些函数之前,您必须添加代码来检查readyList
数组并根据您的偏好对元素重新排序。It can be done, but not easily. You'd have to hack jQuery itself, probably here. Before jQuery starts calling these functions inside the
while
loop, you'd have to add code to inspect thereadyList
array and re-order the elements according to your preference.