jquery.ajaxq.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * jQuery AjaxQ - AJAX request queueing for jQuery
  3. *
  4. * Version: 0.0.1
  5. * Date: July 22, 2008
  6. *
  7. * Copyright (c) 2008 Oleg Podolsky (oleg.podolsky@gmail.com)
  8. * Licensed under the MIT (MIT-LICENSE.txt) license.
  9. *
  10. * http://plugins.jquery.com/project/ajaxq
  11. * http://code.google.com/p/jquery-ajaxq/
  12. */
  13. jQuery.ajaxq = function (queue, options) {
  14. // Initialize storage for request queues if it's not initialized yet
  15. if (typeof document.ajaxq == "undefined") document.ajaxq = {q: {}, r: null};
  16. // Initialize current queue if it's not initialized yet
  17. if (typeof document.ajaxq.q[queue] == "undefined") document.ajaxq.q[queue] = [];
  18. if (typeof options != "undefined") // Request settings are given, enqueue the new request
  19. {
  20. // Copy the original options, because options.complete is going to be overridden
  21. var optionsCopy = {};
  22. for (var o in options) optionsCopy[o] = options[o];
  23. options = optionsCopy;
  24. // Override the original callback
  25. var originalCompleteCallback = options.complete;
  26. options.complete = function (request, status) {
  27. // Dequeue the current request
  28. document.ajaxq.q[queue].shift();
  29. document.ajaxq.r = null;
  30. // Run the original callback
  31. if (originalCompleteCallback) originalCompleteCallback(request, status);
  32. // Run the next request from the queue
  33. if (document.ajaxq.q[queue].length > 0) document.ajaxq.r = jQuery.ajax(document.ajaxq.q[queue][0]);
  34. };
  35. // Enqueue the request
  36. document.ajaxq.q[queue].push(options);
  37. // Also, if no request is currently running, start it
  38. if (document.ajaxq.q[queue].length == 1) document.ajaxq.r = jQuery.ajax(options);
  39. }
  40. else // No request settings are given, stop current request and clear the queue
  41. {
  42. if (document.ajaxq.r) {
  43. document.ajaxq.r.abort();
  44. document.ajaxq.r = null;
  45. }
  46. document.ajaxq.q[queue] = [];
  47. }
  48. }