Skip to content

Instantly share code, notes, and snippets.

@alex3305
Last active August 29, 2015 14:07
Show Gist options
  • Save alex3305/597928f837575dddb2f6 to your computer and use it in GitHub Desktop.
Save alex3305/597928f837575dddb2f6 to your computer and use it in GitHub Desktop.
Streaming client for Javascript.
// Streaming function for Javascript, wrapped as a jQuery function.
// @param url URL of the receive.
// @param callback Callback function on when data is received. When no callback is
// provided, the received data will be written to console.log().
(function($) {
$.Stream = function(url, callback) {
var xhr = internalXHR();
var length = 0;
if (callback === undefined) { callback = function(text) { console.log(text); } }
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.status == 200 && xhr.readyState >= 3) {
var text = xhr.responseText;
callback(text.substr(length, text.length - length));
length = xhr.responseText.length;
}
}
xhr.send(null);
return this;
};
function internalXHR() {
return (function(xhr, xObjects, i) {
if (xhr) return new xhr();
for (i = 0; i < xObjects.length; i++) {
try { return new ActiveXObject(xObjects[i]); } catch (e) { }
}
})( window.XMLHttpRequest, ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'] )
};
}(jQuery));
// Based on http://stackoverflow.com/a/3957470
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment