Posted By

bernhardb on 09/26/12


Tagged

image preloader multiple


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

BrockSamsom


Preload images from list and execute callback after


 / Published in: jQuery
 

URL: http://blog.appstack.io

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. }

Report this snippet  

You need to login to post a comment.