codememo

jQuery Ajax는 모든 이미지가 로드될 때까지 기다립니다.

tipmemo 2023. 2. 27. 22:38
반응형

jQuery Ajax는 모든 이미지가 로드될 때까지 기다립니다.

jQuery로 Ajax 콜을 실행하려고 하는데 잘 작동하고 있습니다.성공 이벤트를 사용하여 데이터를 표시합니다.그러나 외부 HTML 파일이 로드되는 즉시 성공이 트리거되는 것 같습니다.큰 이미지가 있으면 표시된 후에도 계속 로드됩니다.모든 것을 다 로드한 후에 내용을 표시하는 방법이 있습니까?코드는 다음과 같습니다.

$('#divajax').html('<br><div style="text-align: center;"><img src="res/ajax-loader.gif"></div>');
$.ajax({
    cache: false,
    url: 'ajax/content.php',
    success: function(data) {
          $('#divajax').html(data);
    }
});

@alex가 쓴 플러그인이 어떤 이유에서인지 작동하지 않았습니다.나는 이유를 알 수 없었다.하지만 그의 코드는 나에게 효과가 있는 더 가벼운 해결책을 생각해내도록 영감을 주었다.그것은 애매한 약속을 사용한다.@alex의 플러그인과 달리 이 플러그인은 요소의 배경 이미지를 고려하지 않고 img 요소만 고려합니다.

// Fn to allow an event to fire after all images are loaded
$.fn.imagesLoaded = function () {

    // get all the images (excluding those with no src attribute)
    var $imgs = this.find('img[src!=""]');
    // if there's no images, just return an already resolved promise
    if (!$imgs.length) {return $.Deferred().resolve().promise();}

    // for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)
    var dfds = [];  
    $imgs.each(function(){

        var dfd = $.Deferred();
        dfds.push(dfd);
        var img = new Image();
        img.onload = function(){dfd.resolve();}
        img.onerror = function(){dfd.resolve();}
        img.src = this.src;

    });

    // return a master promise object which will resolve when all the deferred objects have resolved
    // IE - when all the images are loaded
    return $.when.apply($,dfds);

}

그런 다음 다음과 같이 사용할 수 있습니다.

$.ajax({
    cache: false,
    url: 'ajax/content.php',
    success: function(data) {
        $('#divajax').html(data).imagesLoaded().then(function(){
            // do stuff after images are loaded here
        });
    }
});

그게 누군가에게 도움이 됐으면 좋겠어요.

위의 코드를 사용하면 이미지 중 하나에 오류가 발생한 경우(예를 들어 URL이 잘못되었기 때문에), 약속은 해결되고 오류는 무시됩니다.이것이 필요한 것일 수도 있지만, 상황에 따라서는 이미지 로딩에 실패했을 경우 작업을 중단할 수도 있습니다.이 경우 onerror 행은 다음과 같이 치환할 수 있습니다.

img.onerror = function(){dfd.reject();}

그리고 다음과 같은 오류를 파악합니다.

$('#divajax').html(data).imagesLoaded().done(function(){
    // do stuff after all images are loaded successfully here
}).fail(function(){
    // do stuff if any one of the images fails to load
});

jQuery 플러그인, wait For Images...

$.ajax({
    cache: false,
    url: 'ajax/content.php',
    success: function(data) {

         $('#divajax').html(data).hide().waitForImages(function() {
             $(this).show();
         });

    }
});

그러면 요소가 로딩되어 숨겨지고 하위 항목이 다시 표시됩니다.img요소가 로드되었습니다.

로드 이벤트에 바인딩하여 완료 시기를 알 수 있습니다.

$('<img>').bind('load', function() {
    $(this).appendTo('body');
});

또는 이 플러그인을 사용할 수 있습니다.

이는 모든 img가 개별적으로 로드될 때 트리거됩니다.

$('img').on('load', function() {
      // do something
});

사용:

var loaded = 0;
$('img').on('load', function() {
   loaded++;
   if(loaded == $('img').length){
      // do something
   }
});

JavaScript 및 jQuery와 함께 작동하는 플러그인을 사용할 수 있습니다. ajax 내에서 사용해보십시오.success로드된 콘텐츠에 대한 콜백 함수 및 모든 콘텐츠 숨기기imagesloaded콜백 함수가 트리거되지 않습니다.아래 코드 예를 참조하십시오.

$.ajax({
    cache: false,
    url: 'ajax/content.php',
    success: function(data) {
        var $divajax = $('#divajax').html(data).hide();
        $divajax.imagesLoaded(function() {
             $divajax.show();
         });

    }
});

jquery의 .load() 사용을 검토합니다.

의 설명은 다음과 같습니다.

로드 이벤트는 요소 및 모든 하위 요소가 완전히 로드되면 요소로 전송됩니다.이 이벤트는 이미지, 스크립트, 프레임, iframe 및 window 객체와 관련된 모든 요소로 전송할 수 있습니다.

$('#divajax').html('<br><div style="text-align: center;"><img src="res/ajax-loader.gif"></div>').load(function() {
$.ajax({
    cache: false,
    url: 'ajax/content.php',
    success: function(data) {
          $('#divajax').html(data);
    }
});
});

이 코드를 사용해 보세요.잘 되고 있어요.

$.1940url: "../api/filename",입력: 'GET',success: 기능(기능) {$('#timeout').syslog(timeout);
$('#module img').on"load", function(){module.log img'}).
};});

Daniel의 솔루션에서 플러그인으로 이미지를 찾을 수 없을 때 작은 버그가 발생합니다.

다른 일부에서도 같은 문제가 발생할 경우를 대비해서:

변경:

// if there's no images, just return an already resolved promise
if (!$imgs.length) {return $.Deferred.resolve().promise();}

수신인:

// if there's no images, just return an already resolved promise
    if (!$imgs.length) {
        var dfd = $.Deferred();
        return dfd.resolve().promise();
    }

나는 이것을 사용하는 것이 가장 좋다고 생각한다.

$(window).ready(function(){ //load your ajax})

언급URL : https://stackoverflow.com/questions/4774746/jquery-ajax-wait-until-all-images-are-loaded

반응형