There are cases when you want your JavaScript to save all the images in browser cache so as to avoid loading them required. Let’s say you have a select box where you select something and the corresponding image changes somehow. You can use the following code snippet to store and cache all images returned from an array in your browser cache
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]; } }