The following function implements one of the most basic picture preload effects we want
function Preloadimages (arr) {
var newimages=[]
var arr= (typeof arr!= "Object")? [arr]: arr //ensures that parameters are always arrays
for (var i=0; i<arr.length; i++) {
Newimages[i]=new Image ()
Newimages[i].src=arr[i]
}
}
We can load the picture we want by the following way
Preloadimages ([' 1.gif ', ' 2.gif ', ' 3.gif ')
Preloadimages ([' 1.gif ', ' 2.gif ', ' 3.gif ']). Done (function (images) {
When the picture is all loaded, execute the code here
The images parameter is an array type that corresponds to the loaded image
Images[0] corresponds to the first image
})
function Preloadimages (arr) {
var newimages=[], loadedimages=0
var postaction=function () {}//Add a postaction function here
var arr= (typeof arr!= "Object")? [arr]: arr
function Imageloadpost () {
loadedimages++
if (loadedimages==arr.length) {
Postaction (newimages)///loading complete use we call the Postaction function and pass the newimages array as parameters.
}
}
for (var i=0; i<arr.length; i++) {
Newimages[i]=new Image ()
Newimages[i].src=arr[i]
Newimages[i].onload=function () {
Imageloadpost ()
}
Newimages[i].onerror=function () {
Imageloadpost ()
}
}
return {//Here Returns the Done method for a blank object
Done:function (f) {
postaction=f | | Postaction
}
}
}
The above code, we have slightly modified several places:
First, we add a postaction function, which is used as a callback function after the image is loaded, and the user can overwrite the function with its own handler function when it is called later.
Second, our preloadimages () function returns an empty object that contains a simple done () method, which is the key to implementing this transformation, ensuring the implementation of chained calls.
Finally, our call becomes the following form
Preloadimages ([' 1.gif ', ' 2.gif ', ' 3.gif ']). Done (function (images) {
Alert (images.length)//alerts 3
Alert (images[0].src+ "" +images[0].width)//alerts ' 1.gif 220 '
})
The definition of an array in JS as a parameter pass