Skip to content

Instantly share code, notes, and snippets.

@ninjascribble
Last active December 18, 2015 02:08
Show Gist options
  • Save ninjascribble/70cb507273e07c9c71c2 to your computer and use it in GitHub Desktop.
Save ninjascribble/70cb507273e07c9c71c2 to your computer and use it in GitHub Desktop.
; (function () {
var Controls = Controls || {};
var fallback = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIW2N81d/4HwAHYAL7mbvoAwAAAABJRU5ErkJggg==';
var classname = 'deferred-img';
Controls.Image = function (node, options) {
this.state = 'ready';
this.node = node || document.createElement('figure');
this.loader = new Image();
this.onload = onload.bind(this);
// Configure options
this.fallback = options.fallback || fallback;
this.src = options.src || this.fallback;
this.callback = options.callback || null;
this.callbackDelay = options.callbackDelay || 0;
this.node.classList.add(classname);
}
Controls.Image.prototype.load = function (src) {
this.state = 'loading';
this.src = (src) ? src : this.src;
this.loader.onload = this.loader.onerror = this.onload;
// Kind of a hack, but this will get tossed out as soon as we replace the
// loader. At the moment the resource loads too soon for the CSS transition
// to keep up, causing the asset to POP in.
setTimeout(function () {
this.loader.src = this.src; // kicks off the loading process
}.bind(this), 10);
}
function onload(evt) {
evt.type == 'error' && (this.src = this.fallback);
this.node.style.backgroundImage = 'url("' + this.src + '")';
this.node.classList.add('done');
this.callback && setTimeout(this.callback, this.callbackDelay);
cleanup(this);
};
// TODO: When we implement the loading solution, this will be
// responsible for returning the connection back into the pool,
// or whatever else might need to be done to free up some resources.
function cleanup(mess) {
mess.state = 'done';
mess.loader = mess.callback = mess.callbackDelay = mess.onload = null;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment