Skip to content

Instantly share code, notes, and snippets.

@netgfx
Last active January 4, 2016 15:29
Show Gist options
  • Save netgfx/8641220 to your computer and use it in GitHub Desktop.
Save netgfx/8641220 to your computer and use it in GitHub Desktop.
Load Multiple Images with callbacks
/**
* [loadAssets description]
* @param {[type]} assets [description]
* @return {[type]} [description]
*/
function loadAssets(assets, fn, onFinish) {
var promises = [];
for (var i = 0; i < assets.length; i++) {
var promise = imagePromise(assets[i], assets.length, fn);
promises.push(promise);
}
$.when.apply($, promises).done(function () {
Registry.cachedImages = {};
for (var i = 0; i < arguments.length; i++) {
// from "assets/blah/myImage.jpg to myImage
var splitName = String( $(arguments[i]).attr('src') ).split("/");
splitName = String( splitName[splitName.length - 1] ).split(".");
splitName = splitName[0];
Registry.cachedImages[splitName] = arguments[i];
}
onFinish();
});
}
// Create a Promise for loading an image!
// Basically taking out the useful, tricky, and heavily refined bit from
// http://desandro.github.io/imagesloaded/
function imagePromise(src, length, fn) {
var deferred = $.Deferred();
var img = new Image();
var pool = length - 1;
var currentCount = 0;
var func = fn;
function resolve() {
// Resolution callbacks receive the image, which you can then inject into the DOM
// to avoid triggering an extra HTTP request in IE
func();
return deferred.resolve(img);
}
// Resolution events
$(img).on({
error: deferred.reject,
load: resolve
});
// Attach the source afterwards, since DOM synchronicity is weird:
// A cached image will sometimes load or error on assignment
img.src = src;
// ...But sometimes cached images never fire load!
// In this case they would already be in the DOM at this point. We need to infer it:
if (img.complete && img.naturalWidth !== undefined) {
// And then use setTimeout to resolve asynchronously (otherwise promise is broken!)
setTimeout(resolve);
}
return deferred.promise();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment