public
Last active

Queueing jQuery Ajax requests. Usage $.ajax({queue: true})

  • Download Gist
jquery.ajax.queue.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
$ = jQuery
 
queues = {}
running = false
 
queue = (name) ->
name = 'default' if name is true
queues[name] or= []
 
next = (name) ->
list = queue(name)
 
unless list.length
running = false
return
 
[options, deferred] = list.shift()
 
$.ajax(options)
.always(-> next(name))
.done(-> deferred.resolve(arguments...))
.fail(-> deferred.reject(arguments...))
 
push = (name, options) ->
list = queue(name)
deferred = $.Deferred()
 
list.push([options, deferred])
next(name) unless running
running = true
deferred.promise()
 
remove = (name, options) ->
list = queue(name)
 
for [value, _], i in list when value is options
list.splice(i, 1)
break
 
$.ajaxTransport '+*', (options) ->
if options.queue
queuedOptions = $.extend({}, options)
queuedOptions.queue = false
queuedOptions.processData = false
 
send: (headers, complete) ->
push(options.queue, queuedOptions)
.done (data, textStatus, jqXHR) ->
complete(jqXHR.status,
jqXHR.statusText,
text: jqXHR.responseText,
jqXHR.getAllResponseHeaders())
 
.fail (jqXHR, textStatus, errorThrown) ->
complete(jqXHR.status,
jqXHR.statusText,
text: jqXHR.responseText,
jqXHR.getAllResponseHeaders())
 
abort: ->
remove(options.queue, queuedOptions)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.