In previous lessons we learned various operations on text and strings, today we focus on two different data types: images and objects. After taking this lesson, you will know how to:
Use JavaScript to speed up image exchange.
Create your own objects to make scripts easier to understand.
Use associative arrays to quickly access every object in the script.
One of the main problems with using JavaScript for image transformation is that it doesn’t tell the browser to download that image until it needs to be changed. If you have a large image and want to call it up when the mouse rolls over an image, the browser has to temporarily download the image, which may take a while and greatly reduce the sliding effect.
If your connection speed is slow and the image you want to load is a fairly large image, you will have to wait after placing the mouse on the image. Since some browsers require that the loaded image must be saved in the buffer, sometimes you may not see the effect of the image transformation at all. In order to avoid these annoying problems, we can pre-load the images to be transformed when the page is loaded.
In Web programming, preloading is a technology that downloads images to the cache before they are needed. In this way, when the image is really needed to be displayed, it can be quickly restored from the cache and displayed immediately.
Preloading images is actually not difficult. All you have to do is create a new image object, and then set the name of the image to be preinstalled to the src attribute of the image, as shown below:
var an_image = new Image();
an_image.src = "my_nice_image.gif";
By setting the src attribute of the image, the image can be automatically downloaded to your hard drive (assuming that your cache is available, of course), and then when the image changes, the image will be read directly from the hard drive without having to download it. .
The only thing left to do is how to make the preloaded image happen after the page is downloaded and before the image transformation operation. The delightful thing is that it's easy. The body tag in HTML has an event handler called onLoad, which will be called when the page is loaded. If your body tag looks like this: