ready.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. define([
  2. "../core",
  3. "../core/init",
  4. "../deferred"
  5. ], function( jQuery ) {
  6. // The deferred used on DOM ready
  7. var readyList;
  8. jQuery.fn.ready = function( fn ) {
  9. // Add the callback
  10. jQuery.ready.promise().done( fn );
  11. return this;
  12. };
  13. jQuery.extend({
  14. // Is the DOM ready to be used? Set to true once it occurs.
  15. isReady: false,
  16. // A counter to track how many items to wait for before
  17. // the ready event fires. See #6781
  18. readyWait: 1,
  19. // Hold (or release) the ready event
  20. holdReady: function( hold ) {
  21. if ( hold ) {
  22. jQuery.readyWait++;
  23. } else {
  24. jQuery.ready( true );
  25. }
  26. },
  27. // Handle when the DOM is ready
  28. ready: function( wait ) {
  29. // Abort if there are pending holds or we're already ready
  30. if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
  31. return;
  32. }
  33. // Remember that the DOM is ready
  34. jQuery.isReady = true;
  35. // If a normal DOM Ready event fired, decrement, and wait if need be
  36. if ( wait !== true && --jQuery.readyWait > 0 ) {
  37. return;
  38. }
  39. // If there are functions bound, to execute
  40. readyList.resolveWith( document, [ jQuery ] );
  41. // Trigger any bound ready events
  42. if ( jQuery.fn.triggerHandler ) {
  43. jQuery( document ).triggerHandler( "ready" );
  44. jQuery( document ).off( "ready" );
  45. }
  46. }
  47. });
  48. /**
  49. * The ready event handler and self cleanup method
  50. */
  51. function completed() {
  52. document.removeEventListener( "DOMContentLoaded", completed, false );
  53. window.removeEventListener( "load", completed, false );
  54. jQuery.ready();
  55. }
  56. jQuery.ready.promise = function( obj ) {
  57. if ( !readyList ) {
  58. readyList = jQuery.Deferred();
  59. // Catch cases where $(document).ready() is called after the browser event has already occurred.
  60. // We once tried to use readyState "interactive" here, but it caused issues like the one
  61. // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
  62. if ( document.readyState === "complete" ) {
  63. // Handle it asynchronously to allow scripts the opportunity to delay ready
  64. setTimeout( jQuery.ready );
  65. } else {
  66. // Use the handy event callback
  67. document.addEventListener( "DOMContentLoaded", completed, false );
  68. // A fallback to window.onload, that will always work
  69. window.addEventListener( "load", completed, false );
  70. }
  71. }
  72. return readyList.promise( obj );
  73. };
  74. // Kick off the DOM ready check even if the user does not
  75. jQuery.ready.promise();
  76. });