Check all images uploaded after .ajax request?

I need to know when all images are loaded from an added HTML source to perform another function. How can I check this?

$(document).ready(function () {
  $('a.load-more').click(function (e) {
    e.preventDefault();
    $.ajax({
        type: "GET",
        url: $(this).attr('href'),
        data: {
            page: last_id
        },
        dataType: "script",

        success: function () {
            $('.load-more').show();
        }
    });
  });
});

I add the html source as follows:

$('.container').append('<%= escape_javascript(render(:partial => @items)) %>');

It gives the html source successfully, but I cannot find out when all the images from this source are loaded

.container is updated every time you click a link <a href="/items" class="load-more">Load more</a>

and the source .container looks like this:

<ul class="container">
  <%= render @items %>
</ul>
+2
source share
1 answer

In all browsers that support the event capture phase, you can capture the onload event for all newly added images:

document.addEventListener(
    'load',
    function(event){
        var elm = event.target;
        if( elm.nodeName.toLowerCase() === 'img' && $(elm).closest('.container').length && !$(elm).hasClass('loaded')){ // or any other filtering condition
            console.log('image loaded');
            $(elm).addClass('loaded');
            if($('.container img.loaded').length === $('.container img').length) {          
                // do some stuff
                console.log("All images loaded!")
            }
        }
    },
    true // Capture event
);

, , IE8, , onload DOM, script onload.

+3

Source: https://habr.com/ru/post/1625478/


All Articles