javascriptjquerydomimage-preloader

Preload images and insert into DOM


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!


Solution

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