Skip to content

Instantly share code, notes, and snippets.

@felix-d
Created March 24, 2015 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felix-d/2f6896ad854579df0af0 to your computer and use it in GitHub Desktop.
Save felix-d/2f6896ad854579df0af0 to your computer and use it in GitHub Desktop.
Javascript images preloading by chunks with lodash
//requires lodash
function preload(sources, chunkSize) {
chunkSize = chunkSize || sources.length;
var sourcesChunked = _.chunk(sources, chunkSize);
var steps = sourcesChunked.length;
var current = 0;
var inner = function(_current){
var imagesTemp = [];
var l = sourcesChunked[_current].length;
var counter = 0;
var callback = function(){
console.log("updated counter");
counter++;
if(counter == l - 1){
if(_current < steps - 1){
inner(++_current);
}
else {
// preloading done
}
}
};
for (var i = 0; i < l; i++){
imagesTemp[i] = new Image();
imagesTemp[i].src = sourcesChunked[_current][i];
imagesTemp[i].onload = callback;
}
};
inner(current);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment