JavaScript2017. 12. 20. 13:54

모바일에서는 ajax나 getJSON으로 웹 페이지를 불러올 때 이미지가 있는 경우 뚝뚝 끊길 때가 많다.

네트워크 상태가 안 좋거나 이미지 크기가 크거나 그럴 때.


그래서 이미지가 완전히 로드된 후에 나머지 페이지 처리를 하고 싶었다.

구글링을 하다가 좋은 예제가 있어 담아왔다. 출처는 아래에 ..


먼저 이미지로드를 처리할 확장형 객체를 구현한다.

$.fn.imagesLoaded = function() {
  var $imgs = this.find('img[src!=""]');
  if(!$imgs.length) 
    return $.Deferred().resolve().promise();

  var dfds = [];
  $imgs.each(function() {
    var dfd = $.Deferred();
    dfds.push(dfd);
    var img = new Image();
    img.onload = function() {
      dfd.resolve();
    }
    img.onerror = function() {
      drd.resolve();
    }
    img.src = this.src;
  });
  
  return $.whdn.apply($, dfds);
}

이제 이미지를 로드하는 곳에 붙여넣기만 하면 끝.

$(selector).css('display', 'none');
$(selector).empty();
$.getJSON('/url.do', function(result) {
  ...
  $(selector).append(result.date.imageSrc).imagesLoaded().then(function() {
    $(selector).css('display', 'block');
    // window.android.hideProgressBar();
    // 그 외 나머지 처리할 작업
  });
}

출처 : https://stackoverflow.com/questions/4774746/jquery-ajax-wait-until-all-images-are-loaded


참고로 같은 이름의 플러그인도 있으니 다운받아서 사용하면 더 간단하지 싶다. 

https://github.com/desandro/imagesloaded

Posted by 홍규홍규