Tutorial :image preloader in jquery



Question:

i have this code but i dont know what to do next..

var toBeInsertedToAS = "";    for(j=1;j<=10;j++)  {      $('<img />')      .attr('src','imgUrl_'+j+'.png')      .load(function(){                          toBeInsertedToAS += $(this).attr('src')+"|";                                });      theSetDataCount++;  }      alert(toBeInsertedToAS);  

i just want to have this output..

imgUrl_1.png|imgUrl_2.png|imgUrl_3.png|etc...

but as what i can see, after the loop, there's no output.. maybe because it goes to alert(toBeInsertedToAS) without loading the pictures completely.. i just want to completely load the pictures first before it will execute the alert..


Solution:1

You can rearrange it a bit, like this:

var toBeInsertedToAS = [], theSetDataCount = 0;    for(j=1;j<=10;j++)  {      $('<img />').one('load', function(){                   toBeInsertedToAS.push(this.src);                   if(toBeInsertedToAS.length == theSetDataCount)                       alert(toBeInsertedToAS.join('|'));                }).attr('src','imgUrl_'+j+'.png')                  .each(function() {                    if(this.complete) $(this).load();                });      theSetDataCount++;  }   

You can test it here, this demo loads images from http://dummyimage.com/ as a source.

The load event happens when the image loads, not a synchronous thing, though it will be instant if it's from cache. From cache also won't fire the load event in some browsers...we're manually handling that with the .each() and the .one() ensures it only runs once, not affecting our count in a funny way.

The key here is to fire the alert() (or any other function) when the last load handler runs.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »