5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

複数の画像読み込み後の処理を Deferred で

Last updated at Posted at 2016-04-19

元ネタはこちら。

[ajax/pjax]複数枚の画像読み込み後に処理を実行する

これ、Deferredでやってみたら? と思って書き直してみました。
やってることは同じ。

var startOnLoadImage = function ($target){
  var d = new $.Deferred();
  var targets = [];
  var loaded = 0;
  $target.each(function(i, elm) {
    targets[i] = new Image();
    targets[i].src = elm.src;
  });
  $.each(targets, function(){
    $(this).on('load', function(){
      loaded++;
      if (loaded == targets.length){
        d.resolve();
      }
    });
  });
  return d.promise();
};

こんな風に使う。

$img = $('#sakiNiYonde .image');
startOnLoadImage($img).done(function(){
  // 処理
});

追記

よく考えたら(考えなくても)2回each回す必要なくね?

var startOnLoadImage = function($target) {
  var d = new $.Deferred();
  var loaded = 0;
  var max = $target.length;
  $target.each(function() {
    var targetObj = new Image();
    $(targetObj).on('load', function(){
      loaded++;
      if (loaded == max){
        d.resolve();
      }
    });
    targetObj.src = this.src;
  });
  return d.promise();
};

こんな感じです。 https://jsfiddle.net/kdoq31cq/

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?