[英]How can I call a function at the very end of document.ready
I have multiple document.ready functions on a page and I want a function to be called when all my document.ready functions have been executed. 我在页面上有多个document.ready函数,我希望在执行所有document.ready函数时调用一个函数。 I simply want the function to be called at the very end, after all other document.ready functions have executed.
我只是希望在所有其他document.ready函数执行完毕后,在最后调用该函数。 An example of this could be that each document.ready function increments a global variable when it has been executed, and the last function needs to check the value of that variable at the very end.
一个例子可能是每个document.ready函数在执行时递增一个全局变量,最后一个函数需要在最后检查该变量的值。
Any ideas ? 有任何想法吗 ?
This will be enough: 这就足够了:
$(function () {
window.setTimeout(function () {
// your stuff here
}, 0);
});
This postpones the execution of your function after all other in the document ready queue are executed. 这会在执行文档就绪队列中的所有其他操作后推迟执行您的函数。
First idea (for small apps): Tidy up 第一个想法(适用于小型应用):整理一下
You can just put everything in one $().ready() call. 您可以将所有内容放在一个$()。ready()调用中。 It might nieed refactoring, but it's the right thing to do in most cases.
它可能会破坏重构,但在大多数情况下这是正确的做法。
Second idea: A Mediator [pattern] 第二个想法:中介[模式]
Create a mediator class that will register functions and call its register() instead of $().ready(). 创建一个中介类,它将注册函数并调用其register()而不是$()。ready()。 When all functions are registered You just loop over the collection and run them in the single and only $().ready() and You have a point in code that is just after all is executed.
当所有函数都被注册时你只需循环遍历集合并在单个中运行它们,只有$()。ready()并且你有一个代码点,就在执行之后。
I am currently developing a kind of a framework for jquery applications that has a mediator. 我目前正在为具有中介的jquery应用程序开发一种框架。 I might stick together a small version including the mediator if You're interested.
如果你感兴趣的话,我可能会把一个包括调解员在内的小版本粘在一起。
Why not just calling it after all the others ? 为什么不在所有其他人之后调用呢?
$(function(){
func1();
...
funcN();
functionThatNeedsToBeCalledAfter();
});
Of course you will have to cleanup your code to have only 1 place where the document ready function is used... but then your code would be more readable so it's worth it. 当然,你必须清理你的代码只有一个地方使用文件就绪功能......但是你的代码会更具可读性,所以它是值得的。
little hacky but might work, create a variable inside jquery scope like that 有点hacky但可能会工作,在jquery范围内创建一个变量
$.imDone = false
then create a function with setTimeout called after short time to lookup for the variable ser to true 然后在短时间内调用setTimeout创建一个函数,以查找变量ser为true
var theLastFunctionToCall = function(){ alert('I m the last being called!') } var trigger = function(){ $.imDone?theLastFunctionToCall():window.setTimeout(trigger,10); } trigger();
I only recommend this when u have different $(document).ready in different big js files, but if you can refactor i sincerelly recommend an optimal solution. 当你在不同的大js文件中有不同的$(document).ready时,我只推荐这个,但是如果你可以重构我自己推荐一个最佳的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.