programing

무언가를 실행하기 전에 모든 이미지가 로드될 때까지 기다리는 jQuery의 공식적인 방법

closeapi 2023. 5. 26. 20:59
반응형

무언가를 실행하기 전에 모든 이미지가 로드될 때까지 기다리는 jQuery의 공식적인 방법

이 작업을 수행할 때 jQuery:

$(function() {
   alert("DOM is loaded, but images not necessarily all loaded");
});

DOM이 로드될 때까지 기다렸다가 코드를 실행합니다.모든 영상이 로드되지 않은 경우에도 코드가 실행됩니다.요소를 표시하거나 숨기거나 이벤트를 첨부하는 것과 같은 DOM 항목을 초기화하는 경우 이는 분명히 우리가 원하는 것입니다.

애니메이션이 필요하고 모든 이미지가 로드될 때까지 애니메이션을 실행하지 않습니다.이것을 할 수 있는 공식적인 방법이 jQuery에 있습니까?

내가 가진 가장 좋은 방법은<body onload="finished()">하지만 꼭 필요한 경우가 아니면 그렇게 하고 싶지 않아요.

참고: Internet Explorer의 jQuery 1.3.1에는 실제로 내부에서 코드를 실행하기 전에 모든 이미지가 로드될 때까지 기다리는 버그가 있습니다.$function() { }따라서 해당 플랫폼을 사용하는 경우 위에서 설명한 올바른 동작 대신 제가 원하는 동작을 사용할 수 있습니다.

jQuery를 사용합니다.$(document).ready()DOM이 로드될 때 무언가를 실행하고,$(window).on("load", handler)이미지와 같은 다른 모든 항목도 로드될 때 무언가를 실행합니다.

차이는 의 완전한 파일에서 할 수 . 이 많은 양의 HTML 파일을 있다면 말입니다.jollyrogerNNJPEG 파일(또는 기타 적합한 파일):

<html>
    <head>
        <script src="jquery-1.7.1.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                alert ("done");
            });
        </script>
    </head><body>
        Hello
        <img src="jollyroger00.jpg">
        <img src="jollyroger01.jpg">
        // : 100 copies of this in total
        <img src="jollyroger99.jpg">
    </body>
</html>

그러면 DOM이 해당 지점에서 준비되기 때문에 이미지가 로드되기 전에 경고 상자가 나타납니다.변경하는 경우:

$(document).ready(function() {

대상:

$(window).on("load", function() {

그러면 이미지가 로드될 까지 알림 상자가 나타나지 않습니다.

따라서 전체 페이지가 준비될 때까지 기다리려면 다음과 같은 방법을 사용할 수 있습니다.

$(window).on("load", function() {
    // weave your magic here.
});

저는 이미지가 요소에 로드되었을 때 콜백을 실행하거나 로드된 이미지당 한 번씩 실행할 수 있는 플러그인을 작성했습니다.

은 와유합다니와 .$(window).load(function() { .. })하여 check."를 선택할 수 . 모든 ,#content(예:)가 로드되었습니다. 이 플러그인이 사용자를 위한 플러그인입니다.

CSS에서 로드를 합니다. 를 들어, 또에다같지로원다니합드이한미를서참지조음되는과은▁referen▁it▁as에▁such▁also▁loading다,▁the또▁supports니한▁css원지▁of▁images합다로ced.background-image,list-style-image 타기.

waitForImages jQuery 플러그인

사용 예

$('selector').waitForImages(function() {
    alert('All images are loaded.');
});

jsFiddle의 예.

자세한 설명서는 GitHub 페이지에서 확인할 수 있습니다.

$(window).load()페이지가 처음 로드될 때만 작동합니다.동적 작업(예: 클릭 버튼, 새 이미지가 로드될 때까지 대기)을 수행하는 경우에는 이 작업이 수행되지 않습니다.이를 위해 내 플러그인을 사용할 수 있습니다.

다운로드.

/**
 *  Plugin which is applied on a list of img objects and calls
 *  the specified callback function, only when all of them are loaded (or errored).
 *  @version: 1.0.0 (Feb/22/2010)
 */

(function($) {
$.fn.batchImageLoad = function(options) {
    var images = $(this);
    var originalTotalImagesCount = images.size();
    var totalImagesCount = originalTotalImagesCount;
    var elementsLoaded = 0;

    // Init
    $.fn.batchImageLoad.defaults = {
        loadingCompleteCallback: null, 
        imageLoadedCallback: null
    }
    var opts = $.extend({}, $.fn.batchImageLoad.defaults, options);
        
    // Start
    images.each(function() {
        // The image has already been loaded (cached)
        if ($(this)[0].complete) {
            totalImagesCount--;
            if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
        // The image is loading, so attach the listener
        } else {
            $(this).load(function() {
                elementsLoaded++;
                
                if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);

                // An image has been loaded
                if (elementsLoaded >= totalImagesCount)
                    if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
            });
            $(this).error(function() {
                elementsLoaded++;
                
                if (opts.imageLoadedCallback) opts.imageLoadedCallback(elementsLoaded, originalTotalImagesCount);
                    
                // The image has errored
                if (elementsLoaded >= totalImagesCount)
                    if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
            });
        }
    });

    // There are no unloaded images
    if (totalImagesCount <= 0)
        if (opts.loadingCompleteCallback) opts.loadingCompleteCallback();
};
})(jQuery);

다음 시간 후에 요청된 단일 이미지의 다운로드 완료에 대한 알림을 받으려는 사용자용$(window).loadfires, 요소의, 이지요를 할 수 .load이벤트

예:

// create a dialog box with an embedded image
var $dialog = $("<div><img src='" + img_url + "' /></div>");

// get the image element (as a jQuery object)
var $imgElement = $dialog.find("img");

// wait for the image to load 
$imgElement.load(function() {
    alert("The image has loaded; width: " + $imgElement.width() + "px");
});

지금까지 어떤 대답도 가장 간단한 해결책을 제시하지 못했습니다.

$('#image_id').load(
  function () {
    //code here
});

는 을사하는것좋습다니이용을 사용하는 것을 합니다.imagesLoaded.jsJavascript 라러리

jQuery를 사용하지 $(window).load()?

https://stackoverflow.com/questions/26927575/why-use-imagesloaded-javascript-library-versus-jquerys-window-load/26929951 에서 답변한 바와 같이

그것은 범위의 문제입니다.를 사용하면 이미지할 수 Images Loaded(영상 로드됨)는 이미지 세트를 대상으로 지정할 수 .$(window).load()는 모든 이미지, 개체, .js 및 .vmdk 파일 및 프레임을 포함한 모든 자산을 대상으로 합니다.대부분의 경우, 이미지로드된 시간이 다음보다 빠릅니다.$(window).load()더 작은 자산을 목표로 하기 때문입니다.

로드된 이미지를 사용해야 하는 다른 좋은 이유

  • IE8+에서 공식 지원
  • 라이선스: MIT 라이선스
  • 종속성: 없음
  • 무게 (최소화 & gzip) : 7kb 최소화 (경량!)
  • 다운로드 빌더(무게를 줄이는 데 도움이 됨): 필요 없음, 이미 작습니다.
  • Github에서 : 예
  • 커뮤니티 & 기여자: 14,000명 이상의 꽤 큰 회원들, 비록 13명의 기여자들에 불과하지만.
  • 역사 및 기여: 비교적 오래된(2010년 이후) 프로젝트만큼 안정적이지만 여전히 활동 중인 프로젝트

자원.

jQuery와 함께라면 나는 이것과 함께...

$(function() {
    var $img = $('img'),
        totalImg = $img.length;

    var waitImgDone = function() {
        totalImg--;
        if (!totalImg) alert("Images loaded!");
    };

    $('img').each(function() {
        $(this)
            .load(waitImgDone)
            .error(waitImgDone);
    });
});

데모: http://jsfiddle.net/molokoloco/NWjDb/

이렇게 하면 선택한 내용에 따라 다른 용기 또는 본문 내부의 모든 이미지가 로드될 때 작업을 실행할 수 있습니다.순수한 질문입니다. 플러그진이 필요 없습니다.

var counter = 0;
var size = $('img').length;

$("img").load(function() { // many or just one image(w) inside body or any other container
    counter += 1;
    counter === size && $('body').css('background-color', '#fffaaa'); // any action
}).each(function() {
  this.complete && $(this).load();        
});

이미지 사용패키지된 v3.1.8(최소화된 경우 6.8Kb)을 로드했습니다.비교적 오래된(2010년 이후) 프로젝트이지만 여전히 활성화되어 있습니다.

github: https://github.com/desandro/imagesloaded 에서 찾을 수 있습니다.

그들의 공식 사이트:

사용하는 것보다 더 나은 이유:

$(window).load() 

이미지를 동적으로 로드하고 싶을 수도 있기 때문입니다. jsfiddle

$('#button').click(function(){
    $('#image').attr('src', '...');
});

저의 해결책은 molokoloco와 비슷합니다.jQuery 함수로 작성:

$.fn.waitForImages = function (callback) {
    var $img = $('img', this),
        totalImg = $img.length;

    var waitImgLoad = function () {
        totalImg--;
        if (!totalImg) {
            callback();
        }
    };

    $img.each(function () {
        if (this.complete) { 
            waitImgLoad();
        }
    })

    $img.load(waitImgLoad)
        .error(waitImgLoad);
};

예:

<div>
    <img src="img1.png"/>
    <img src="img2.png"/>
</div>
<script>
    $('div').waitForImages(function () {
        console.log('img loaded');
    });
</script>

@Luca Matteis Here: https://www.examplefiles.net/cs/508021 에서 이 솔루션을 찾았습니다.

하지만 다음과 같이 약간 편집했습니다.

function showImage(el){
    $(el).removeClass('hidden');
    $(el).addClass('show');

    $(el).prev().removeClass('show');
    $(el).prev().addClass('hidden');
}

<img src="temp_image.png" />
<img class="hidden" src="blah.png" onload="showImage(this);"/>

언급URL : https://stackoverflow.com/questions/544993/official-way-to-ask-jquery-wait-for-all-images-to-load-before-executing-somethin

반응형