Last active
May 3, 2018 06:08
-
-
Save bruth/4745365 to your computer and use it in GitHub Desktop.
jQuery override to Ajax method to support queuing requests. A deferred object is returned to act as a proxy when the request is actually sent. By default, GET requests are not queued unless the `queue` option is `true`.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(root, factory) { | |
if (typeof define == 'function' && define.amd) { | |
define(['jquery'], function(jQuery) { | |
factory(jQuery); | |
}); | |
} else { | |
factory(root.jQuery); | |
} | |
})(this, function(jQuery) { | |
var ajax = jQuery.ajax, | |
requestQueue = [], | |
requestPending = false; | |
function sendRequest(options, promise, trigger) { | |
var complete, error, options, params, success, that = this; | |
if (trigger !== false) trigger = true; | |
if (trigger) requestPending = true; | |
success = options.success; | |
error = options.error; | |
complete = options.complete; | |
params = { | |
complete: function(xhr, status) { | |
if (complete) complete.apply(that, arguments); | |
if (trigger) dequeueRequest(); | |
}, | |
success: function() { | |
if (success) success.apply(that, arguments); | |
promise.resolveWith(this, arguments); | |
}, | |
error: function() { | |
if (error) error.apply(this, arguments); | |
promise.rejectWith(this, arguments); | |
} | |
}; | |
ajax(jQuery.extend({}, options, params)); | |
}; | |
function dequeueRequest() { | |
var args, options, promise; | |
if ((args = requestQueue.shift())) { | |
options = args[0], promise = args[1]; | |
sendRequest(options, promise); | |
} else { | |
requestPending = false; | |
} | |
}; | |
function queueRequest(options) { | |
var promise, type, queue; | |
promise = $.Deferred(); | |
type = (options.type || 'get').toLowerCase(); | |
queue = options.queue != null ? options.queue : (type === 'get' ? false : true) | |
if (queue && requestPending) { | |
requestQueue.push([options, promise]); | |
} else { | |
sendRequest(options, promise, queue); | |
} | |
return promise; | |
}; | |
jQuery.ajax = function(options) { | |
return queueRequest(options); | |
}; | |
jQuery.hasPendingRequest = function() { | |
return requestPending; | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment