Skip to content

Instantly share code, notes, and snippets.

@diegocasmo
Last active August 29, 2015 14:10
Show Gist options
  • Save diegocasmo/9904eb72263b08f128dc to your computer and use it in GitHub Desktop.
Save diegocasmo/9904eb72263b08f128dc to your computer and use it in GitHub Desktop.
Helper object to preload images.
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