ready.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. // 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. }
  42. } );
  43. jQuery.ready.then = readyList.then;
  44. // The ready event handler and self cleanup method
  45. function completed() {
  46. document.removeEventListener( "DOMContentLoaded", completed );
  47. window.removeEventListener( "load", completed );
  48. jQuery.ready();
  49. }
  50. // Catch cases where $(document).ready() is called
  51. // after the browser event has already occurred.
  52. // Support: IE <=9 - 10 only
  53. // Older IE sometimes signals "interactive" too soon
  54. if ( document.readyState === "complete" ||
  55. ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
  56. // Handle it asynchronously to allow scripts the opportunity to delay ready
  57. window.setTimeout( jQuery.ready );
  58. } else {
  59. // Use the handy event callback
  60. document.addEventListener( "DOMContentLoaded", completed );
  61. // A fallback to window.onload, that will always work
  62. window.addEventListener( "load", completed );
  63. }
  64. } );