Step 2: Load an Image File into the Object
The image object created above is empty. It has no image file associated with it. To load an image into the object, simply update the code as follows:
The Image object, represented by the my_image variable, now contains the someimage.jpg image. As a result, that image has now been loaded into the browser's cache.
Demonstration of Preloading
To demonstrate the preloading of the image, I will use the following code. This code creates an empty image object, then allows the user to press a button to load the image. The image in this example is 6.2 MB in size, so it will take a while to load even on a broadband connection.
Using the onload image event, a function will be called as soon as the image has finished loading, notifying the user that the image has been loaded into the cache.
To demonstrate this, I wrote the following code. First, you can press a button to preload the image. After it has finished loading, the page displays a button that allows you to use the preloaded image in an image tag, using only the image filename. Even though we aren't using the variable that we loaded the image into, the image will still show up right away because it's in the cache.