Skip to content

Instantly share code, notes, and snippets.

@weblancaster
Last active August 29, 2015 13:58
Show Gist options
  • Save weblancaster/9958193 to your computer and use it in GitHub Desktop.
Save weblancaster/9958193 to your computer and use it in GitHub Desktop.
Snippet to how to preload images assets using javascript.
function preloadimages(arr) {
var newimages = []
, loadedimages = 0
, postaction = function() {}
, arr = ( typeof arr != "object" ) ? [arr] : arr
, i = 0;
function imageloadpost(){
loadedimages++;
if ( loadedimages == arr.length ) {
postaction( newimages ) //call postaction and pass in newimages array as parameter
}
}
for ( ; i < arr.length; i++ ){
newimages[i] = new Image();
newimages[i].src = arr[i];
newimages[i].onload = function() {
imageloadpost();
}
newimages[i].onerror = function() {
imageloadpost();
}
}
return { //return blank object with done() method
done: function(f){
postaction = f || postaction //remember user defined callback functions to be called when images load
}
}
}
// How to use it?!
var arr = [
'_res/images/Gallery/img01.png',
'_res/images/Gallery/img02.png',
'_res/images/Gallery/img03.png'
];
preloadimages(preLoadedImgs).done(function(images){
for ( var i = 0; i < images.length; i++ ) {
console.log('image src' + images[i].src + 'preloaded!' );
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment