jquery에서 이미지 미리 불러오기

조회수 5082회

자바스크립트에서 이미지를 미리 불러오는 가장 빠르고 쉬운 방법을 찾고있는데요. 이게 중요한지는 모르겠지만 jquery를 쓰고있습니다.

인터넷에서 아래같은 소스를 발견했는데요.

function complexLoad(config, fileNames) {
  for (var x = 0; x < fileNames.length; x++) {
    $("<img>").attr({
      id: fileNames[x],
      src: config.imgDir + fileNames[x] + config.imgFormat,
      title: "The " + fileNames[x] + " nebula"
    }).appendTo("#" + config.imgContainer).css({ display: "none" });
  }
};

이거말고 좀더 간단하고 빠른 소스는 없을까요?

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기
    function preload(arrayOfImages) {
        $(arrayOfImages).each(function(){
            $('<img/>')[0].src = this;
            // Alternatively you could use:
            // (new Image()).src = this;
        });
    }
    
    // 사용법  :
    
    preload([
        'img/imageName.jpg',
        'img/anotherOne.jpg',
        'img/blahblahblah.jpg'
    ]);
    
    

    이거나 jQuery를 쓰신다면 아래같은 방법도 있습니다.

    $.fn.preload = function() {
        this.each(function(){
            $('<img/>')[0].src = this;
        });
    }
    
    // 사용법 :
    
    $(['img1.jpg','img2.jpg','img3.jpg']).preload();
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)