×

Welcome to TagMyCode

Please login or create account to add a snippet.
1
0
 
0
Language: Javascript
Posted by: Jing Tai Piao
Added: Aug 30, 2012 11:23 PM
Views: 65
$("#items li").each(function(idx) {

// queue up an ajax request
$.ajaxQueue({
url: '/ajax_html_echo/',
data: {html : "["+idx+"] "+$(this).html()},
type: 'POST',
success: function(data) {
// Write to #output
$("#output").append($("<li>", { html: data }));
}
});
});
  1. /*
  2. * jQuery.ajaxQueue - A queue for ajax requests
  3. *
  4. * (c) 2011 Corey Frang
  5. * Dual licensed under the MIT and GPL licenses.
  6. *
  7. * Requires jQuery 1.5+
  8. */
  9. (function($) {
  10.  
  11. // jQuery on an empty object, we are going to use this as our Queue
  12. var ajaxQueue = $({});
  13.  
  14. $.ajaxQueue = function( ajaxOpts ) {
  15.     var jqXHR,
  16.         dfd = $.Deferred(),
  17.         promise = dfd.promise();
  18.  
  19.     // queue our ajax request
  20.     ajaxQueue.queue( doRequest );
  21.  
  22.     // add the abort method
  23.     promise.abort = function( statusText ) {
  24.  
  25.         // proxy abort to the jqXHR if it is active
  26.         if ( jqXHR ) {
  27.             return jqXHR.abort( statusText );
  28.         }
  29.  
  30.         // if there wasn't already a jqXHR we need to remove from queue
  31.         var queue = ajaxQueue.queue(),
  32.             index = $.inArray( doRequest, queue );
  33.  
  34.         if ( index > -1 ) {
  35.             queue.splice( index, 1 );
  36.         }
  37.  
  38.         // and then reject the deferred
  39.         dfd.rejectWith( ajaxOpts.context || ajaxOpts,
  40.             [ promise, statusText, "" ] );
  41.  
  42.         return promise;
  43.     };
  44.  
  45.     // run the actual query
  46.     function doRequest( next ) {
  47.         jqXHR = $.ajax( ajaxOpts )
  48.             .done( dfd.resolve )
  49.             .fail( dfd.reject )
  50.             .then( next, next );
  51.     }
  52.  
  53.     return promise;
  54. };
  55.  
  56. })(jQuery);

1 comment

Greg Milby 4 years ago
I"ve been using this for a couple of years now - really seems to prevent bottlenecks onload with heavy front ends

Write a comment