I use this to display images only after they are loaded into the browser's memory. I need Javascript codes to tell me if the image is ready to be displayed or processed. For example, there is a huge image that I need to display but the size is too big. I display a loading icon before I reveal the image so that it looks more like a contemporary (jQuery equipped) web page. I use the following Javascript codes.
<script> var loaded_img = new Array(); var image_list = new Array("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"); // the list of potential images that you want to check later var img1loaded = false; function installOnloadAlarm() { var i; for (i=0; i<image_list.length; i++) { // iterate all images var img = new Image(); // create an image object img.onload = function() { // set up onload actions var match_result = this.src.match(/\/(\w+\.\w+)$/); // match filename after the last '/' loaded_img.push(match_result[1]); // push match result into loaded_img array }; img.src = "image/"+image_list[i]+".jpg"; // by setting the source, the browser will start loading (assume images are in 'image' directory) } } function checkLoadedImg(imgFilename) { var i; for (i=0; i<loaded_img.length; i++) { if (imgFilename == loaded_img[i]) { return true; } } return false; } function afterLoaded() { if (img1loaded) { clearInterval(timer1); clearInterval(timer2); . . . do your post loading job . . . } } installOnloadAlarm(); var timer1 = setInterval(function(){img1loaded = checkLoadedImg('1.jpg');},200); // need to set timer to check as the result won't be available instantly (this example checks only '1.jpg') var timer2 = setInterval(function(){afterLoaded();},200); </script> |
The timers are necessary as the results won't be available after installing the onload conditions. This is just a brief example of a complete image file checking system whether the image is loaded into browser.
No comments:
Post a Comment