0

i have this function to create new images to load them in memory

function preloadImgs() {
var imgDomain = "http://imgs.domain/";
if (document.images) {
    var img1 = new Image();
    var img2 = new Image();
    var img3 = new Image();

    img1.src = imgDomain + "images/1/cover.jpg";
    img2.src = imgDomain + "images/2/cover.jpg";
    img3.src = imgDomain + "images/3/cover.jpg";
} } 

// initialize the function 
preloadImgs()

i need a way to know when all images in preloadImgs() function have been loaded , how can i achive that using the same code that i have provided ?

1 Answers1

0

You can use a promise pattern.

https://developers.google.com/web/fundamentals/getting-started/primers/promises

Although these aren't natively supported everywhere, jQuery (tagged) provides an implementation:

https://api.jquery.com/promise/

Combined with img.onload to resolve the promises you can respond to an array of promises by:

var arrayOfPromises = [];
var $deferred = $.Deferred();
var img = new Image();
img.onload = function() {
    // Check your support needs @ http://caniuse.com/#search=naturalWidth
    if (img.naturalWidth && img.naturalHeight) {
       $deferred.resolve()
    } else {
       $deferred.reject();
    }
 };
 img.onerror = $deferred.reject;
 img.src = 'someimage.png';

 arrayOfPromises.push($deferred);

 $.when.apply($, arrayOfPromises).then(function() {
   // your callback, images all loaded
   alert('OK')
 }, function() {
   // Any failed image load occur
   alert('FAIL')
 });
AndFisher
  • 633
  • 1
  • 5
  • 18