Question

Hi I have a question about preloading images either in JS or jQuery. What I have is one image which I basically want to be repeated 16 times in a

<li>image here</li>

structure. I started out by basically inserting it into the list as is like this.

<ul>
   <li>image</li>
   <li>image</li>
   <li>image</li>
</ul>

16 times in my HTML. Works but not very pretty nor efficient. If I want to preload the image in my js and then insert into my HTML list. I have found some different ways of doing it here.

Here they are cached but then I need to put them in the li. Any good suggestions?! Both JS and jQuery examples are welcome.

Thanks!

Was it helpful?

Solution

var img = new Image();
img.onload = function() {
  $("li").prepend( this );
};
img.src = 'http://placehold.it/40x40/cf5';

OTHER TIPS

After you cache your image (using the code http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript/) you simple run a javascript loop:

for (i=0; i<16; i++) {
  $('ul#your_ul_id').append('<li><img src="your_image_url"/></li>');
}

I would trigger a .load() event for the original image and only then clone the DOM:

$(document).ready(function() {
var img = $('<img id="yourImg">'); 
img.load(function() {
// repeat this step ad libitum
$(this).clone().appendTo(whatever)
});
img.attr('src', yourURL);
img.appendTo(whatever2);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top