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

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

+5
source share
3 answers

Yes.

From jQuery function ready 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 );
}
+14
source

Yes, it is safe. There are several ways to install such handlers in jQuery, and the only "unsafe" one is $(document).bind("ready", handler). From jQuery docs :

All three of the following syntaxes are equivalent:

  • $(document).ready(handler)
  • $().ready(handler) ( )
  • $(handler)

$(document).bind("ready", handler). , : , .bind("ready") . , .

+4

Yes. You can put it inside a function and it will fire when you call this function.

+1
source

All Articles