Reputation: 7391
I need to know when all images are loaded from appended html source to perform another function. How can I check that?
$(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'm appending html source like this:
$('.container').append('<%= escape_javascript(render(:partial => @items)) %>');
It gives html source successfully, but I can't find out when all images from that source is loaded
.container updates every time link is clicked <a href="/items" class="load-more">Load more</a>
and the .container source looks like this:
<ul class="container">
<%= render @items %>
</ul>
Upvotes: 3
Views: 1703
Reputation: 74420
On all browsers supporting event capturing phase, you can capture onload event for all new 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
);
To support e.g IE8 which doesn't handle capturing phase, you should set onload event to specific images once they are added in the DOM, setting it in script
onload event.
Upvotes: 5