最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it safe to call $(document).ready() from inside a function? - Stack Overflow

programmeradmin0浏览0评论

If I use the $(document).ready() handler from within a function, will it still guarantee that the code inside it will only be run if the document is ready, even if the document ready event has occurred well in the past?

If I use the $(document).ready() handler from within a function, will it still guarantee that the code inside it will only be run if the document is ready, even if the document ready event has occurred well in the past?

Share Improve this question edited Dec 5, 2022 at 7:54 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Aug 22, 2011 at 1:41 T NguyenT Nguyen 3,4152 gold badges34 silver badges51 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 14

Yes.

From the jQuery ready function source.

// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
    // Handle it asynchronously to allow scripts the opportunity to delay ready
    return setTimeout( jQuery.ready, 1 );
}

Yes, that is safe. jQuery has several ways to set handlers like this, and the only "unsafe" one is $(document).bind("ready", handler). From the jQuery docs:

All three of the following syntaxes are equivalent:

  1. $(document).ready(handler)
  2. $().ready(handler) (this is not recommended)
  3. $(handler)

There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.

Yes. You can put it inside a function, and it'll fire whenever you call that function.

发布评论

评论列表(0)

  1. 暂无评论