Skip to content

Instantly share code, notes, and snippets.

@andru255
Forked from shawnbot/load-queue.js
Created September 20, 2013 04:11
Show Gist options
  • Save andru255/6633198 to your computer and use it in GitHub Desktop.
Save andru255/6633198 to your computer and use it in GitHub Desktop.
var loadQueue = function() {
var q = queue(),
defer = q.defer,
dispatch = d3.dispatch("progress", "complete"),
requests = [];
q.defer = function(load, url) {
return defer(function(callback) {
var req = load(url, function(error, data) {
req.loaded = req.total;
req.progress = 1;
update();
callback.apply(null, arguments);
})
.on("progress", function() {
var e = d3.event;
req.loaded = e.loaded;
req.total = e.total;
req.progress = e.loaded / e.total;
});
req.total = req.loaded = req.progress = 0;
requests.push(req);
});
};
function update() {
var total = 0,
loaded = 0,
progress = 0;
requests.forEach(function(req) {
total += req.total;
loaded += req.loaded;
progress += req.progress;
});
progress /= requests.length;
dispatch.progress({
total: total,
loaded: loaded,
progress: progress
});
if (progress >= 1) {
dispatch.complete({
loaded: loaded
});
}
}
d3.rebind(q, dispatch, "on");
return q;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment