Skip to content

Instantly share code, notes, and snippets.

@terion-name
Last active August 29, 2015 14:16
Show Gist options
  • Save terion-name/8c2a02a7cd89a97ac4d9 to your computer and use it in GitHub Desktop.
Save terion-name/8c2a02a7cd89a97ac4d9 to your computer and use it in GitHub Desktop.
Images preload via promises
# helpers
# $ = jQuery
# See: http://learn.jquery.com/code-organization/deferreds/examples/
# Generic asynchronous cache
$.createCache = (requestFunction)->
cache = {};
return (key, callback)->
if ( !cache[key] )
cache[key] = $.Deferred((defer)->
requestFunction(defer, key)
).promise()
return cache[key].done(callback)
# load image via defer (promise)
$.loadImage = $.createCache (defer, url)->
image = new Image()
cleanUp = -> image.onload = image.onerror = null
defer.then cleanUp, cleanUp
image.onload = -> defer.resolve image
image.onerror = defer.reject
image.src = url
# client code
imagesFiles = ['img1.jpg', 'img2.jpg', 'img3.jpg']
promise = $.when.apply null, imagesFiles.map (url)-> $.loadImage url
promise.fail -> alert 'Something went wrong'
promise.done (img1, img2, img3)-> # do smth
// helpers
// $ - jQuery
// See: http://learn.jquery.com/code-organization/deferreds/examples/
// Generic asynchronous cache
$.createCache = function(requestFunction) {
var cache;
cache = {};
return function(key, callback) {
if (!cache[key]) {
cache[key] = $.Deferred(function(defer) {
return requestFunction(defer, key);
}).promise();
}
return cache[key].done(callback);
};
};
// load image via defer (promise)
$.loadImage = $.createCache(function(defer, url) {
var cleanUp, image;
image = new Image();
cleanUp = function() {
return image.onload = image.onerror = null;
};
defer.then(cleanUp, cleanUp);
image.onload = function() {
return defer.resolve(image);
};
image.onerror = defer.reject;
return image.src = url;
});
// client code
var imagesFiles = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
var promise = $.when.apply(null, imagesFiles.map(function(url) {
return $.loadImage(url);
}));
promise.fail(function() {
alert('Something went wrong');
});
promise.done(function(img1, img2, img3) {
// do smth
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment