/ Published in: jQuery
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.
I use it in various cases working with Phonegap to get my app a better native experience.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * 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; }); } }