Skip to content

Instantly share code, notes, and snippets.

@bepatrickdavid
Created October 7, 2016 09:52
Show Gist options
  • Save bepatrickdavid/27b05477f029ca86df4dd212f6631117 to your computer and use it in GitHub Desktop.
Save bepatrickdavid/27b05477f029ca86df4dd212f6631117 to your computer and use it in GitHub Desktop.
JS: Preload images after all page is load
function preloadImages(array) {
if (!preloadImages.list) {
preloadImages.list = [];
}
var list = preloadImages.list;
for (var i = 0; i < array.length; i++) {
var img = new Image();
img.onload = function() {
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.push(img);
img.src = array[i];
}
}
$(window).bind("load", function() {
preloadImages(images);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment