Return to Snippet

Revision: 59717
at September 26, 2012 20:49 by bernhardb


Initial Code
/**
 * Imagepreloader load each image in given array/numeric object
 *
 * NOTICE:
 * Callback will never be executed if there's one nonexisting image
 * 
 * SOLUTION:
 * Add two more lines with iCallbackAfter--; into the error and abort callback handler
 *
 * Copyright 2012, Bernhard Bezdek
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * @param {array/numeric object} oImageList
 * @param {function} callback
 */
function preloadImages(oImageList, callback) {
	if ( typeof (oImageList) == 'object' && typeof (callback) === "function") {
		var iCallbackAfter = oImageList.length;

		var iPreloadInterval = window.setInterval(function() {
			if (iCallbackAfter === 0) {
				window.clearInterval(iPreloadInterval);
				callback();
			}
		}, 100);

		$.each(oImageList, function(iIndex, sImage) {
			oImageList[iIndex] = new Image();
			oImageList[iIndex].onload = function(oResult) {
				iCallbackAfter--;
			};
			oImageList[iIndex].onabort = function(oResult) {
				console.log(oResult);
			};
			oImageList[iIndex].onerror = function(oResult) {
				console.log(oResult);
			};
			if (!sImage.match('http://')) {
				sImage = sImage;
			}

			oImageList[iIndex].src = sImage;
		});
	}
}

Initial URL
http://blog.appstack.io

Initial Description
If you have a list of images and want'them all to preload before page is shown. This function is very useful.
I use it in various cases working with Phonegap to get my app a better native experience.

Initial Title
Preload images from list and execute callback after

Initial Tags
image

Initial Language
jQuery