Last active
August 29, 2015 14:10
-
-
Save diegocasmo/9904eb72263b08f128dc to your computer and use it in GitHub Desktop.
Helper object to preload images.
This file contains 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
define([ | |
'jquery', | |
'underscore' | |
], function ($, _) { | |
var ImageHelper = { | |
initialize: function () { | |
var example = [ | |
"img/image1.jpg", | |
"img/image2.jpg" | |
]; | |
this.preloader(example, function() { | |
// images have been loaded | |
}); | |
}, | |
/** | |
* data: an array of images | |
* callback: function to execute after | |
* all images have been loaded | |
*/ | |
preloader: function(data, callback) { | |
var promises = []; | |
for (var i = 0; i < data.length; i++) { | |
(function(url, promise) { | |
var img = new Image(); | |
$(img).one('load', function() { | |
promise.resolve(); | |
}; | |
img.src = url; | |
})(data[i], promises[i] = $.Deferred()); | |
} | |
$.when.apply($, promises).done(function() { | |
callback(); | |
}); | |
} | |
}; | |
return ImageHelper; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment