Last active
August 29, 2015 14:16
-
-
Save terion-name/8c2a02a7cd89a97ac4d9 to your computer and use it in GitHub Desktop.
Images preload via promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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