0

I am using Javascript to change the image when the radio button is clicked. When you first load the page there is a delay after each radio button is clicked and then afterwards it runs smoothly. I am guessing this is from it not loading the image until the radio is clicked and I was wondering if there is a way to do this. The javascript is as follows:

<script type="text/javascript">


var switchingImage;
var productid;

function changeImage()
  {
    switchingImage.src = this.value;
    productId.value = this.alt;
  }


window.onload = function() {
var radios = document.getElementById('imageSwitcher').getElementsByTagName('input');
var products = document.getElementById('imageSwitcher').getElementsByTagName('alt');

switchingImage = document.getElementById('imageToSwitch');
productId = document.getElementById('productToSwitch');

for(var i=0;i<radios.length;i++)
{
    radios[i].onclick = changeImage;
}
}

</script>
  • Check out [this post](http://stackoverflow.com/questions/2936778/jquery-preload-an-image-on-request-with-a-callback-function). – Oybek Feb 01 '12 at 21:53

2 Answers2

0

To preload an image:

new Image().src = "path/to/file/image.png";

The image will be downloaded and stored in cache for use.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Sure, just make an array of images and then reference them later. The line of code switchingImage.src = this.value; would instead reference the array. When placing the preloaded images into the array, make sure to use the new keyword. For example:

var preLoad = new Array();
var firstImage = new Image();
firstImage.src = "someLocation/thisImage.jpg";
preLoad.push(firstImage);

Doing this for all your images, and then referencing the array preLoad[imageNumber].src for use in switchingImage.src is how the preloaded images would be collected.

Travis J
  • 81,153
  • 41
  • 202
  • 273