Skip to content

Instantly share code, notes, and snippets.

@etoxin
Created May 24, 2016 07:02
Show Gist options
  • Save etoxin/a3c7015491c1617fd61f6a130fec1919 to your computer and use it in GitHub Desktop.
Save etoxin/a3c7015491c1617fd61f6a130fec1919 to your computer and use it in GitHub Desktop.
cacheImagesThenCallback
/**
* Pass an Array of image urls and it will run `callback` once they are cached.
*
* @example
cacheImagesThenCallback([image.jpg, picture.png], function() {
...
});
* @alias CORE.cacheImagesThenCallback
* @constructor
* @param imageSrcArray {array} Array of image urls.
* @param callback {function} Callback function
*/
var cacheImagesThenCallback = function (imageSrcArray, callback) {
/**
* @type {number} Load Status
*/
var loadStatus = 1;
/**
* Checks to see if all images have been loaded.
*/
function checkLoadStatus () {
loadStatus === imageSrcArray.length ? callback() : loadStatus++;
}
/**
* We go through every url and load it in memory.
* We then check the status of the the entire array of images on load.
*/
imageSrcArray.forEach(function(item){
var img = new Image();
img.src = item;
img.onload = checkLoadStatus;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment