简体   繁体   中英

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

如果我从函数内部使用$(document).ready()处理函数,即使过去文档就绪事件发生得很好,它是否仍保证仅在文档就绪后才运行其中的代码?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM