Preloading images in javascript

chris (2004-06-09 12:22:51)
1126 views
0 replies
It's wise to preload images when a site loads to enable smooth transitions on rollovers and other events. In this example I have three images - one of a button and two more of the button in a 'hover' state and 'click' state.
<script language="javascript">
        var button = new Image();
        var buttonhover = new Image();
        var buttonclick = new Image();
                                                                                                                             
        // drag the images up and plop then on local disc
        button.src="images/button_arrow_.gif";
        buttonhover.src="images/button_arrow_hover.gif";
        buttonclick.src="images/button_arrow_pressed.gif";
        doPreload();
        function doPreload(){
           var the_images = new Array('images/button.gif','images/button_hover.gif','images/button_pressed.gif');
           preloadImages(the_images);
        }
        function preloadImages(the_images_array) {
           for(var loop = 0; loop < the_images_array.length; loop++){
                var an_image = new Image();
                an_image.src = the_images_array[loop];
           }
        }
</script>

These images have now been loaded up to the client and cached locally for quick access.

christo
Digg it! Submit to Slashdot Add to Blinklist Del.icio.us Add to Newsvine Add to Technorati Add it to Google Bookmarks Add to Magnolia
comment