js图片预加载代码片段分享

快乐打工仔 分类:实例代码

本章节分享一段代码片段,它是实现图片预加载的核心代码部分。

当然实现的方式有许多种,这里是其中的一种方式,不过原理都是大同小异,需要的朋友可以做一下参考。

代码实例如下:

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);
      };
      oImageList[iIndex].src = sImage;
    });
  }
}

回复

我来回复
  • 暂无回复内容