tube
Version:
Experimental Resource Loader implementing using Server Sent Events
100 lines (78 loc) • 3.06 kB
JavaScript
var tube = (function() {
function Manifest() {
this.resources = [];
}
Manifest.prototype = {
add: function(data) {
// add the resource
this.resources.push(data);
}
};
Object.defineProperty(Manifest.prototype, 'files', {
get: function() {
return this.resources.map(function(resource) {
return resource.path;
});
}
});
if (typeof module != 'undefined' && module.exports) {
module.exports = Manifest;
}
function Tube(endpoint, opts) {
// ensure we have opts
opts = opts || {};
// initialise the number of connections
this.multi = opts.multi || 2;
// initialise the separator
this.separator = opts.separator || String.fromCharCode(0x214B);
// initialise the event sources
this.sources = this.connect(endpoint);
}
Tube.prototype = {
/**
## connect(endpoint: String)
*/
connect: function(endpoint) {
var connections = [],
separator = this.separator;
// initialise the connections
for (var ii = 0; ii < this.multi; ii++) {
connections[ii] = new EventSource(endpoint + '?p=' + ii);
}
console.log(separator);
// handle connection behaviour
connections.forEach(function(connection) {
connection.addEventListener('exception', function(evt) {
console.log('received exception', evt.data);
}, false);
connection.addEventListener('resource', function(evt) {
var resource, script, text;
// parse the data
try {
resource = JSON.parse(evt.data);
// create a script tag
script = document.createElement('script');
// create a text node for the script content
script.appendChild(
document.createTextNode(resource.data.split(separator).join('\n'))
);
// add the script to the document
document.body.appendChild(script);
}
catch (e) {
}
});
connection.addEventListener('done', function(evt) {
console.log('received done', evt);
connection.close();
}, false);
});
return connections;
}
};
// mixin asevented
// asEvented.call(Tube.prototype);
return function(endpoint, opts) {
return new Tube(endpoint, opts);
};
}());