Searching for answers I found this thread using jQuery Deferred for loading several images and waiting before going on:
Wait for image to be loaded before going on.
I'd like to implement this in my code but there's a point I didn't understand yet. In which context or scope can I use these image objects. Or how can I adapt the answer of the thread above in order to provide these images in an image repository.
In detail (as in the thread above):
var imagesLoaded = false;
var imageRepository = new function() {
function loadSprite(src) {
var deferred = $.Deferred();
var sprite = new Image();
sprite.onload = function() {
deferred.resolve();
};
sprite.src = src;
return deferred.promise();
}
var loaders = [];
loaders.push(loadSprite('1.png'));
loaders.push(loadSprite('2.png'));
loaders.push(loadSprite('3.png'));
$.when.apply(null, loaders).done(function() {
imagesLoaded = true;
});
}
Are the images (sprites) created with new in the function loadSprite() accessible in imageRepository, e.g., like imageRepository.sprite1?
My idea was doing something like
var imageRepository = new function() {
...
this.sprite1 = loadSprite('1.png');
}
But loadSprite() returns the deferred promise object.
Am I totally wrong with this idea?