SoFunction
Updated on 2025-03-01

Image object in js and preload processing examples

Image objects not displayed in the document

For Image objects not displayed in the document, defined with the var statement:
Copy the codeThe code is as follows:

var myImage = new Image(); or
var myImage = new Image(<image address string>);

Then you can treat myImage variables like normal Image objects. But since it is not displayed in the document, the following properties: lowsrc, width, height, vspace, hspace, border are of no use. Generally, there is only one use of this kind of object: preload. Because when assigning the src attribute of the object, the entire document reading and JavaScript running are paused, allowing the browser to concentrate on reading the pictures. After reading the picture before reading it, the image copy will be available in the browser cache. When you really want to put the picture in the document, the picture can be displayed immediately. There are often some image connections in web pages today. When the mouse points to it, the image is replaced with another image, and they all pre-read the image first.

JavaScript examples for pre-read images
Copy the codeThe code is as follows:

var imagePreload = new Image();

= '';
= '';
= '';

The above examples are suitable for pre-reading a small number of pictures.
Copy the codeThe code is as follows:

function imagePreload() {
var imgPreload = new Image();
for (i = 0; i < ; i++) {
= arguments[i];
}
}

imagePreload('', '', '', '', '');

The above examples are suitable for pre-reading a large number of pictures.

Because of the caching problems that many browsers have. When the image has been loaded once, if there is another request for the image, since the browser has cached the image, it will not initiate a new request, but will directly load it in the cache. After analysis, you can use the Image attribute - complete, which is compatible with each browser. So make a judgment on this value before the image onload event, as shown in the following example:
Copy the codeThe code is as follows:

function loadImage(url, callback) {
var img = new Image(); //Create an Image object to implement pre-download of images
= url;

if () { // If the image already exists in the browser cache, call the callback function directly
(img);
return; // Return directly, no need to process the onload event
}

= function () { //Callback function asynchronously when the image is downloaded.
(img);//Replace this in the callback function with an Image object
};
};