这段代码可以在页面打开前对图片进行预加载,这个函数非常有用,可以给用户带来更好的体验。
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; }); } }