Fire an event after preloading images

前端 未结 10 1918
北海茫月
北海茫月 2020-12-25 15:25

This is the code I use to preload images, I\'m not sure if it\'s the best one. My question is, how can I fire and event, for an example alert(); dialog after is has finished

10条回答
  •  南方客
    南方客 (楼主)
    2020-12-25 15:56

    Based on answer from Ben Clayton above.

    There can be case where images load fail all together and one must still be able to get callback.

    Here is my revised answer. One ca easily find out hom many images loaded with success and how many ended up in error. this in callback will have that info

    preloadImages(_arrOfImages, function() {
      var response = this;
      var hasError = response.errored.length + response.aborted.length;
      if (hasError > 0) {
        console.log('failed ' + hasError);
      } else {
        console.log('all loaded');
      }
    });
    

    // JSFIDDLE: https://jsfiddle.net/bababalcksheep/ds85yfww/2/

    var preloadImages = function(preload, callBack) {
      var promises = [];
      var response = {
        'loaded': [],
        'errored': [],
        'aborted': []
      };
      for (var i = 0; i < preload.length; i++) {
        (function(url, promise) {
          var img = new Image();
          img.onload = function() {
            response.loaded.push(this.src);
            promise.resolve();
          };
          // Use the following callback methods to debug
          // in case of an unexpected behavior.
          img.onerror = function() {
            response.errored.push(this.src);
            promise.resolve();
          };
          img.onabort = function() {
            response.aborted.push(this.src);
            promise.resolve();
          };
          //
          img.src = url;
        })(preload[i], promises[i] = $.Deferred());
      }
      $.when.apply($, promises).done(function() {
        callBack.call(response);
      });
    };
    

提交回复
热议问题