doc-ready.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*!
  2. * docReady v1.0.4
  3. * Cross browser DOMContentLoaded event emitter
  4. * MIT license
  5. */
  6. /*jshint browser: true, strict: true, undef: true, unused: true*/
  7. /*global define: false, require: false, module: false */
  8. ( function( window ) {
  9. 'use strict';
  10. var document = window.document;
  11. // collection of functions to be triggered on ready
  12. var queue = [];
  13. function docReady( fn ) {
  14. // throw out non-functions
  15. if ( typeof fn !== 'function' ) {
  16. return;
  17. }
  18. if ( docReady.isReady ) {
  19. // ready now, hit it
  20. fn();
  21. } else {
  22. // queue function when ready
  23. queue.push( fn );
  24. }
  25. }
  26. docReady.isReady = false;
  27. // triggered on various doc ready events
  28. function onReady( event ) {
  29. // bail if already triggered or IE8 document is not ready just yet
  30. var isIE8NotReady = event.type === 'readystatechange' && document.readyState !== 'complete';
  31. if ( docReady.isReady || isIE8NotReady ) {
  32. return;
  33. }
  34. trigger();
  35. }
  36. function trigger() {
  37. docReady.isReady = true;
  38. // process queue
  39. for ( var i=0, len = queue.length; i < len; i++ ) {
  40. var fn = queue[i];
  41. fn();
  42. }
  43. }
  44. function defineDocReady( eventie ) {
  45. // trigger ready if page is ready
  46. if ( document.readyState === 'complete' ) {
  47. trigger();
  48. } else {
  49. // listen for events
  50. eventie.bind( document, 'DOMContentLoaded', onReady );
  51. eventie.bind( document, 'readystatechange', onReady );
  52. eventie.bind( window, 'load', onReady );
  53. }
  54. return docReady;
  55. }
  56. // transport
  57. if ( typeof define === 'function' && define.amd ) {
  58. // AMD
  59. define( [ 'eventie/eventie' ], defineDocReady );
  60. } else if ( typeof exports === 'object' ) {
  61. module.exports = defineDocReady( require('eventie') );
  62. } else {
  63. // browser global
  64. window.docReady = defineDocReady( window.eventie );
  65. }
  66. })( window );