从列表中预加载图像,然后执行回调

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从列表中预加载图像,然后执行回调相关的知识,希望对你有一定的参考价值。

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.
  1. /**
  2.  * Imagepreloader load each image in given array/numeric object
  3.  *
  4.  * NOTICE:
  5.  * Callback will never be executed if there's one nonexisting image
  6.  *
  7.  * SOLUTION:
  8.  * Add two more lines with iCallbackAfter--; into the error and abort callback handler
  9.  *
  10.  * Copyright 2012, Bernhard Bezdek
  11.  * Dual licensed under the MIT or GPL Version 2 licenses.
  12.  *
  13.  * @param {array/numeric object} oImageList
  14.  * @param {function} callback
  15.  */
  16. function preloadImages(oImageList, callback) {
  17. if ( typeof (oImageList) == 'object' && typeof (callback) === "function") {
  18. var iCallbackAfter = oImageList.length;
  19.  
  20. var iPreloadInterval = window.setInterval(function() {
  21. if (iCallbackAfter === 0) {
  22. window.clearInterval(iPreloadInterval);
  23. callback();
  24. }
  25. }, 100);
  26.  
  27. $.each(oImageList, function(iIndex, sImage) {
  28. oImageList[iIndex] = new Image();
  29. oImageList[iIndex].onload = function(oResult) {
  30. iCallbackAfter--;
  31. };
  32. oImageList[iIndex].onabort = function(oResult) {
  33. console.log(oResult);
  34. };
  35. oImageList[iIndex].onerror = function(oResult) {
  36. console.log(oResult);
  37. };
  38. if (!sImage.match('http://')) {
  39. sImage = sImage;
  40. }
  41.  
  42. oImageList[iIndex].src = sImage;
  43. });
  44. }
  45. }

以上是关于从列表中预加载图像,然后执行回调的主要内容,如果未能解决你的问题,请参考以下文章

Glide:在内存缓存中预加载图像(有或没有磁盘缓存)

在 SpriteKit 中预加载纹理

如何在 vue 项目中预加载图片

将活动回调发送到片段

使用回调异步加载列表视图中的图像

如何使用接口将活动回调返回到片段