Preload images from list and execute callback after


/ Published in: jQuery
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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. }

URL: http://blog.appstack.io

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.