How to monitor if an image loads completed.
18 November 2010
Recently, a requirement about display images using JS came to me.
The requirement is like: in a div, display 3 images. After 6 seconds, display 3 other images. The problem is: the images have to go across the Internet, and the end user will wait when the images are loading.
And I came with a solution:
Use 2 types of image loading. Type 1 is traditional loading and type 2 have a loading completed function.
Using 2 divs (called div1 and div2) to contain image.
At the beginning, display 3 images using type1 on div1 and hide div2 and start the loading function.
The loading function will get the next 3 images' addresses from the server, start loading the them using type2 onto div2, initialize a loadingImageCount variable as 3, and schedule a check function after 6 seconds.
The type 2 image loading completed function will decrease the loadingImageCount variable by 1.
The check function will check the loadingImageCount variable. If it is greater than 0, schedule a check function after 1 second and end. Otherwise, it will use animation to swap div1 and div2, swap the reference of div1 and div2 (so the next calling of the loading function will affects div2 at that time or div1 at this time because div2 at this time is displayed and div1 at this time is hide for preparing the next 3 images), and start the loading function.
(Red means image loading type. Green means function name. Blue means variable name.)
Then here is the unusual part: how to implement type 2 of image loading that have a loading completed function?
How to monitor if an image loads completed?
After searching for some time, many suggests a DOM object's variable called readyState. My testing shows it can work on IE8 and Firefox 3.6
Here is the function:
function handleImageLoad(imgDom, fn) {
if (imgDom.readyState == "complete") {
fn.call(this);
} else {
imgDom.onreadystatechange = function() {
if (imgDom.readyState == "complete") {
fn.call(this);
}
}
}
}
The usage is like:
handleImageLoad(document.getElementById('img1'), function() {
alert('loaded');
});
It is not perfect. It might lost monitering when the image is loaded after checking and before function registering. Another better way is create an image object using JS, register the onreadystatechange on it, and then change its src. However, this one is generally enough for my usage this time.