JavaScript: Preload ImagesLocation: Tutorials > JavaScript > Here
This tutorial will show you an easy way to preload images to prevent lag, especially in dynamically generated HTML. An example is on the right. The images are changed every second with JavaScript and without preloading, the images don't get loaded until it is their turn at being shown. The benefit of preloading should be apparent now, it loads the images so they are readily available. The coding behind this is incredibly simple and so is the concept. It uses an array of images and loads them into a new "Image object". All this means is that the image gets loaded but you don't see it but when that image needs to be accessed, it will show up instantly because the same image already exists! If you still don't understand, use the code and then it should be clearer.
<script language="javascript" type="text/javascript">
<!-- // the number in the brackets below is the number of images to be used, 100 is used to allow for more images, as long as it is more than the number of images you expect to preload, then it is fine var preloaded = new Array(100); function load_images(imagearray){ for( i=0; i<imagearray.length; i++ ){ preloaded[i] = new Image() preloaded[i].src = imagearray[i] } } //--> </script> The function works like this, the image array is fed into the function (note that at the moment there is no image array). The function then counts the number of images in that array and then makes a new "Image object" for each image. The function above is what preloads the images, but the function has to be called and an image array has to be provided. <!-- this is the image that is modified by the change_image() function. It is important that you leave id="random_image" as that is how the JavaScript idenitifies the image --> <img src="firstimage.gif" alt="Random Image" id="random_image" class="border" /> <script language="javascript" type="text/javascript"> <!-- // the number in the brackets below is the number of images to be used var images = new Array(4) // this is the list of images that will be used in the random selection // use this form: images[x] = 'pathtoimage.gif'; // note the first element must have the number 0 images[0] = '/images/imageone.gif'; images[1] = '../imagetwo.gif'; images[2] = 'images/imagethree.jpg'; images[3] = 'http://example.com/picture.gif'; // call the function to preload the images in the array above load_images(images); //--> </script> |