Jump To Content

LearnHub




Javascript: Image Preloader

A very simple way to load the images into the browsers cache so when they are displayed they will not have to load the file and create a delay in the browser.

// Initiate the image count variable
var imageCount = 0;
// create an array to contain the preloaded image files
var preloadImages = new Array();

// Main function to load new image into browser
function preload(imageFile)
{
imageCount++;
preloadImages[imageCount] = new Image();
preloadImages[imageCount].src = imageFile;
}

// Basic function to load the images when the browser has loaded the webpage.
window.onload = function() {
preload('images/1.jpg');
preload('images/2.jpg');
preload('images/3.jpg');
preload('images/4.jpg');
preload('images/5.jpg');
}


  1. jza saidThu, 22 May 2008 21:25:40 -0000 ( Link )

    What is the new Image() is that a pre-set function or is just builted arbitrary. (i.e. new MyRandomImage() ). Is that the same case in [ImageCount].src?

    Actions
    Vote
    Current Rating
    0
    Rate Up
    Rate Down
    No Votes

    Post Comments

  2. laurellion saidFri, 23 May 2008 02:32:11 -0000 ( Link )

    I’m defining the image object with a new keyword. The code line defines an image object called new Image(). Can be named to your coding preference. And the same goes with imageCount, it is my own naming convention for the array. They are not defined words for functions in the javascript library.

    Actions
    Vote
    Current Rating
    0
    Rate Up
    Rate Down
    No Votes

    Post Comments

Your Comment
Textile is Enabled (View Reference)