Skip to content

Instantly share code, notes, and snippets.

@nopjia
Created September 24, 2015 22:59
Show Gist options
  • Save nopjia/743f2acc7abf298868b9 to your computer and use it in GitHub Desktop.
Save nopjia/743f2acc7abf298868b9 to your computer and use it in GitHub Desktop.
Progressive ArrayBuffer Loading
var stringToArrayBuffer = function(str, soffset, buf, boffset) {
var ui8a = new Uint8Array(buf, boffset);
for (var si = soffset, ai = 0; si < str.length; si++, ai++)
ui8a[ai] = (str.charCodeAt(si) & 0xff);
};
var loadBufferProgressive = function(url, cb) {
var req = new XMLHttpRequest();
req.open("GET", url);
req.overrideMimeType("text/plain; charset=x-user-defined");
var buffer;
var bufferOffset = 0;
req.onprogress = function(e) {
if (req.status !== 200)
return;
// first time alloc buffer
if (!buffer) {
// NOTE: length should be specified, Content-Length not always reliable
var length = parseInt(req.getResponseHeader("Content-Length"));
buffer = new ArrayBuffer(length);
}
var byteLoaded = req.responseText.length;
var byteLength = buffer.byteLength;
stringToArrayBuffer(req.responseText, bufferOffset, buffer, bufferOffset);
bufferOffset = byteLoaded; // update offset
cb(buffer, byteLoaded, byteLength);
};
req.send();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment