1. Create a new object using the Image() constructor.
2. Assign a graphic file to the src property of the new Image object.
3. Assign the src property of the new Image object to the src property of an element.
In the following code, the src attribute of the element named myImage is initially set to an empty string "". In the script section, a new Image object named newImage is created. The newImage object is used to save and access the memory cache containing the image file. A file named graphic.jpg is assigned to the src property of the newImage object. The src property of the newImage object is then assigned to the src property of the element.
Be sure to understand that in the preceding code, the graphic.jpg file is not assigned directly to the src property of the element. Instead, the newImage object is assigned to the src property of the element. If you assigned the graphic.jpg file directly to the src property of the element using the statement document.myImage.src = "graphic.jpg";, then the file would reload from its source each time it was needed. The newImage object opens the file once and saves it to a memory cache.
The following code shows a version of the unicycle animation code modified to use image caching. The lines that add each image file to the unicycle array have been replaced by a for loop, which assigns a new object to each element of the unicycle array until the loadImages variable is greater than the length of the array. In the while loop, each object in the unicycle array is assigned an image file using the src property. In the turn() function, the unicycle[curUnicycle] operator in the statement document.images.src = unicycle [curUnicycle]; now includes the src property so that the statement reads document.images.