Skip to content

Instantly share code, notes, and snippets.

@tdreyno
Created September 2, 2012 22:36
Show Gist options
  • Save tdreyno/3605248 to your computer and use it in GitHub Desktop.
Save tdreyno/3605248 to your computer and use it in GitHub Desktop.
JSON/Swiffy PxLoader extension
// @depends PxLoader.js
/**
* PxLoader plugin to load swiffy
*/
function PxLoaderSwiffy(name, tags, priority) {
var self = this,
loader = null,
complete = false;
this.tags = tags;
this.priority = priority;
var data = null;
this.start = function(pxLoader) {
// we need the loader ref so we can notify upon completion
loader = pxLoader;
var xhr = new XMLHttpRequest();
xhr.open("GET", name, false);
xhr.onreadystatechange = function() {
if (xhr['readyState'] !== 4) { return; }
if (xhr['status'] !== 200) {
loader.onError(self);
return;
}
var serverResponse = xhr['responseText'];
try {
data = JSON.parse(serverResponse);
loader.onLoad(self);
} catch (e) {
loader.onError(self);
}
}
xhr.send(null);
};
// called by PxLoader to check status of image (fallback in case
// the event listeners are not triggered).
this.checkStatus = function() {
if (complete) {
loader.onLoad(self);
}
};
// called by PxLoader when it is no longer waiting
this.onTimeout = function() {
if (complete) {
loader.onLoad(self);
} else {
loader.onTimeout(self);
}
};
// returns a name for the resource that can be used in logging
this.getName = function() {
return name;
};
this.getData = function() {
return data;
}
}
// add a convenience method to PxLoader for adding an image
PxLoader.prototype.addSwiffy = function(name, tags, priority) {
var swiffyLoader = new PxLoaderSwiffy(name, tags, priority);
this.add(swiffyLoader);
// return the img element to the caller
return swiffyLoader.name;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment