Below is the source code for a function that preloads images onto a page, the author has added in some comments to explain how the code works, but I still do not fully understand all of it. to be specific, He claims that the return value of this function is an empty object with a “done()” method that calls the predefined anonymous function, “postaction()”. Is the user of this code supposed to enter his/her own code into the empty postaction function on line 2? If that’s how it works, then what does “postaction=f || postaction” in the return object do?
Source code:
function preloadimages(arr){
var newimages=[], loadedimages=0
var postaction=function(){}
var arr=(typeof arr!="object")? [arr] : arr
function imageloadpost(){
loadedimages++
if (loadedimages==arr.length){
postaction(newimages) //call postaction and pass in newimages array as parameter
}
}
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 { //return blank object with done() method
done:function(f){
postaction=f || postaction
//remember user defined callback functions to be called when images load
}
}
}
link to author’s page:http://www.javascriptkit.com/javatutors/preloadimagesplus.shtml
You can enter your own function for postaction, although it’s not a callback function like you might expect.
However, it returns an object with a done function in it.
If you do soth. like
your function will be executed. If you don’t provide the fnction as a parameter of done, the default postaction will be called and do nothing, since it is an empty function