Monday, 13 June 2011

How to Monitor If an Image Loads Completed - HTML and Javascript Tips

Recently, a requirement about display images using Javascript came to me. The requirement is to display 3 images in a div tag and after 6 seconds, it should display 3 other images. The problem is that the images have to be loaded from a remote Internet site, so that the end user will have to wait when the images are loading.


Here is how I came up a solution:


Use 2 types of image loading. Type 1 is a traditional loading and type 2 has 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 without any bugs.


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'); });

(Please refer to web design blog for colored coding version.) It is not perfect though. It might not be able to monitor when the image is loaded after checking and before the function registering. Another better way is create an image object using JS, register the onreadystatechange on it, and then change its SRC. However, the above method is generally enough for current usage this time.


24K Design Studio Pte Ltd is an innovative Singapore web design and SEO company providing corporate website design, content management system, ecommerce solution and search engine optimization (SEO).

No comments:

Post a Comment