0

I have this code

var html = '';
data.forEach(function (item, index) {
   html += '<img src="' + item.src + '">';
}
$('.container').append(html);

How do I wait until the images are preloaded before displaying them?

I saw something like that :

var img=new Image();
img.src=url;

But how do I know when the images have finished being preloaded in order to call the append() function ?

Vald
  • 237
  • 2
  • 8

1 Answers1

0

The difference in your two examples is that one is creating the images through the Image API while the other is doing it through string concatenation.

The anti how to wait till all the images have load is to set a conditional that test if they all been created.

var html = '';
data.forEach(function (item, index) {
   if( data[index] !== -1){
       html += '<img src="' + item.src + '">';
   } else {
       $('.container').append(html);
   }
}
andre mcgruder
  • 1,120
  • 1
  • 9
  • 12