An example of an Image object in js and its preloading

  • 2020-03-29 23:53:18
  • OfStack

An Image object that is not displayed in a document

For the Image object not displayed in the document, var statement is used to define:
 
var myImage = new Image(); or  
var myImage = new Image(< Image address string >); 

Then you can treat the myImage variable like a normal Image object. However, since it is not displayed in the document, the following properties: lowsrc, width, height, vspace, hspace, border are not useful. Usually this object has only one use: preload. Because when the SRC attribute of the object is assigned, the entire document is read and the JavaScript is suspended, leaving the browser focused on reading the image. After the image is read in advance, the browser has a Copy of the image in its cache, and the image can be displayed immediately when the image is actually put into the document. Web pages now often have some image links, when the mouse pointing at it, the image into another image, they are the first to read the image.

JavaScript example of prereading images
 
var imagePreload = new Image(); 

imagePreload.src = '001.gif'; 
imagePreload.src = '002.gif'; 
imagePreload.src = '003.gif'; 

The above examples are suitable for prereading a small number of images.
 
function imagePreload() { 
var imgPreload = new Image(); 
for (i = 0; i < arguments.length; i++) { 
imgPreload.src = arguments[i]; 
} 
} 

imagePreload('001.gif', '002.gif', '003.gif', '004.gif', '005.gif'); 

The above examples are suitable for prereading a large number of images.

Because of the caching problems that many browsers have. After the Image has been loaded once, if there is another request for the Image, the browser will not launch a new request because it has already cached the Image. Instead, it will directly ask the cache to load it. After analysis, the Image property compatible with each browser can be used --complete. So make a judgment on this value before the image onload event, as shown in the following example:
 
function loadImage(url, callback) { 
var img = new Image(); //Create an Image object to pre-download the Image
img.src = url; 

if (img.complete) { //If the image already exists in the browser cache, call the callback function directly
callback.call(img); 
return; //Return directly, without having to deal with the onload event
} 

img.onload = function () { //The callback function is called asynchronously when the image is downloaded.
callback.call(img);//Replaces this of the callback function with an Image object
}; 
}; 

Related articles: