ready.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. define( [
  2. "../core",
  3. "../var/document",
  4. "../core/readyException",
  5. "../deferred"
  6. ], function( jQuery, document ) {
  7. "use strict";
  8. // The deferred used on DOM ready
  9. var readyList = jQuery.Deferred();
  10. jQuery.fn.ready = function( fn ) {
  11. readyList
  12. .then( fn )
  13. // Wrap jQuery.readyException in a function so that the lookup
  14. // happens at the time of error handling instead of callback
  15. // registration.
  16. .catch( function( error ) {
  17. jQuery.readyException( error );
  18. } );
  19. return this;
  20. };
  21. jQuery.extend( {
  22. // Is the DOM ready to be used? Set to true once it occurs.
  23. isReady: false,
  24. // A counter to track how many items to wait for before
  25. // the ready event fires. See #6781
  26. readyWait: 1,
  27. // Hold (or release) the ready event
  28. holdReady: function( hold ) {
  29. if ( hold ) {
  30. jQuery.readyWait++;
  31. } else {
  32. jQuery.ready( true );
  33. }
  34. },
  35. // Handle when the DOM is ready
  36. ready: function( wait ) {
  37. // Abort if there are pending holds or we're already ready
  38. if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
  39. return;
  40. }
  41. // Remember that the DOM is ready
  42. jQuery.isReady = true;
  43. // If a normal DOM Ready event fired, decrement, and wait if need be
  44. if ( wait !== true && --jQuery.readyWait > 0 ) {
  45. return;
  46. }
  47. // If there are functions bound, to execute
  48. readyList.resolveWith( document, [ jQuery ] );
  49. }
  50. } );
  51. jQuery.ready.then = readyList.then;
  52. // The ready event handler and self cleanup method
  53. function completed() {
  54. document.removeEventListener( "DOMContentLoaded", completed );
  55. window.removeEventListener( "load", completed );
  56. jQuery.ready();
  57. }
  58. // Catch cases where $(document).ready() is called
  59. // after the browser event has already occurred.
  60. // Support: IE <=9 - 10 only
  61. // Older IE sometimes signals "interactive" too soon
  62. if ( document.readyState === "complete" ||
  63. ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
  64. // Handle it asynchronously to allow scripts the opportunity to delay ready
  65. window.setTimeout( jQuery.ready );
  66. } else {
  67. // Use the handy event callback
  68. document.addEventListener( "DOMContentLoaded", completed );
  69. // A fallback to window.onload, that will always work
  70. window.addEventListener( "load", completed );
  71. }
  72. } );