Last active
August 29, 2015 13:57
-
-
Save seanupton/9902518 to your computer and use it in GitHub Desktop.
JavaScript Geometric ajax request batching
This file contains 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
// premise: | |
// all items in collection of AJAX-loaded content have about same complexity. | |
// | |
// first item in a collection should be loaded as quickly as possible, as it | |
// is the first item to be seen. | |
// | |
// But generally, larger batch sizes are more efficient, for fewer requests | |
// | |
// the closer to the end of the collection, the larger the batch size. | |
// | |
// A geometric (doubling) sequence is likely more efficient for these | |
// conditions, than say Fibonacci. | |
// | |
// Copyright (c) 2014, The University of Utah | |
// MIT licensed: https://teamspace.upiq.org/trac/wiki/Copyright | |
(function ($) { | |
function geometric_batch(length) { | |
var r = [], | |
size = 1, | |
pos = 0; | |
while (size <= length) { | |
r.push([pos, Math.min(size, length-pos)]); | |
pos = pos + size; | |
size += size; // 1, 2, 4, 8, 16, 32,...N | |
} | |
return r; | |
} | |
var baseurl = 'http://example.com/api/thisAndThat?'; | |
$(document).ready(function () { | |
var total = $('.somediv').length, | |
batch_spec = geometric_batch(total); | |
batch_spec.forEach(function (pair) { | |
var pos = pair[0], | |
size = pair[1], | |
url = baseurl + 'b_size=' + size + '&b_start=' + pos; | |
$.ajax({ | |
url: url, | |
success: function (response) { | |
return; // do something! | |
}); | |
}); | |
}); | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment