Ticket #6844 (closed feature: duplicate)
Simple way for plugins to delay the ready event
|Reported by:||dareed||Owned by:|
Some plugins will need to load resources dynamically and asynchronously, and may wish for the jQuery ready event to wait until those resources are available, which may be as late as after the window.onload event.
The purpose for delaying the ready event might be for any reason though. Asynchronous loading via a script loader is the canonical example, but ideally jQuery would make no assumptions. An app developer could use it for example to delay lighting up the page with jQuery plugins until some UI interaction event occurs, for example.
This is the simplest way I could imagine it, and only adds a few lines of code to jQuery, and relies on no new globals or jQuery fns.
// delay the event jQuery.ready(false);
This tells jQuery something is running and the ready event shouldn't fire. Of course, this is ignored if it has already fired. Also, this can be called any number of times by any number of plugins. Each time it is called, a corresponding 'true' signal must be sent:
// signal its ok to continue jQuery.ready(true);
If the DOM is ready per the usual semantics, and no one else had signaled 'false', this raises the ready event immediately. If the DOM is not ready yet or other 'false' signals were sent, it waits.
Internally there's just a counter. Each call with 'false' increments it, and each call with 'true' decrements it. If the counter is less than or equal to 0, the event fires (assuming the DOM is also ready).