Skip to content

Instantly share code, notes, and snippets.

@pvdz
Created May 29, 2012 12:38
Show Gist options
  • Save pvdz/2828179 to your computer and use it in GitHub Desktop.
Save pvdz/2828179 to your computer and use it in GitHub Desktop.
NCA fallback library
var NCA = function(type, version, compiler){
this.type = type;
this.version = version;
// compiler must have interface method "compile",
// which accepts a string as single argument
this.compiler = compiler;
};
NCA.prototype = {
queue: [],
fetching: false,
run: function(callback){
this.callback = callback;
var scripts = Array.prototype.slice.call(document.querySelectorAll('script'), 0);
// find all scripts with type="jsq" and version="1.0"
scripts.filter(function(s){
return s.getAttribute('type') == 'jsq' && s.getAttribute('version') == '1.0';
}).forEach(function(s){
this.queue.push(s);
this.next();
},this);
},
next: function(){
if (!this.queue.length) {
if (this.callback) this.callback();
} else if (!this.fetching) {
this.fetching = true;
var next = this.queue.shift();
if (next.src) {
this.GET(next.src+'?'+Math.random(), function(err, src){
if (err) {
this.fetching = false;
throw new Error(err);
} else {
this.process(src, next.src);
}
}.bind(this));
} else {
this.process(next.textContent);
}
}
},
process: function(src, url){
var compiled = this.compiler.compile(src);
var script = document.createElement('SCRIPT');
script.textContent = compiled;
script.className = 'compiled-script';
script.setAttribute('data-src-url', url || 'inline');
document.body.appendChild(script);
// prev appendChild is blocking...
this.fetching = false;
this.next();
},
GET: function(url, callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
try { xhr.status; // status is a getter, this checks for exception
} catch (errrr) {
callback(new Error("Warning: Unknown error with server request (timeout?)."));
}
if (xhr.status == 200) callback(null, xhr.responseText);
else callback(new Error("File request problem (code: "+xhr.status+")!"));
}
};
xhr.open("GET", url);
xhr.send(null);
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment