Preloading images added on the fly using JQuery

702 views Asked by At

I am adding some images to a div from a database in the Page_Load() event. When you hover over one of these black and white images, you see the colour image. I would like to pre-load the colour images but am having issues doing it. My current code loops through all the images, and adds the following:

<script type="text/javascript">
<!-- 
$(document).ready(function() { 
    $("<img />").attr("src", "%s").load(function(){ 
        $("body").append($(this)); 
    }); 
});
--></script>

to a RegisterClientScriptBock where %s is the path to the image. I have tried with and without appending it to the body but neither seem to work. From what I can see, this seems to be the way to pre-load images but I am open to other suggestions. Am I having issues because I am doing it on the fly?

Thanks.

2

There are 2 answers

1
Matrym On BEST ANSWER

Have you thought about creating a div that's absolutely positioned -10000px left and top, height/width 1px, and then throwing all of the images in there with html? I'm not sure why you'd need to use js for this one.

1
Alexandros B On

Maybe this will help?

http://www.yourhtmlsource.com/images/preloading.html

<script type="text/javascript">
<!-- hide from non JavaScript Browsers

Image1= new Image(150,20)
Image1.src = "pic1.gif"

Image2 = new Image(10,30)
Image2.src = "pic2.gif"

Image3 = new Image(72,125)
Image3.src = "pic3.gif"

// End Hiding -->
</script>
  • Image1= new Image is the first step of setting up a new script effect for an image
  • (150,20) are the width and height, respectively, of this image
  • Image1.src = "pic1.gif" gives the source of the image.