Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLHttpRequest JS Image loading

I want to create a website which loads a image via XMLHttpRequest(). (XMLHttpRequest because I want to represent the user a % progressbar)

My Code:

var req = new XMLHttpRequest();  

req.addEventListener("progress", onUpdateProgress, false);  
req.addEventListener("load", onTransferComplete, false);  
req.addEventListener("error", onTransferFailed, false);  
req.addEventListener("abort", onTransferFailed, false);  

req.open("GET", "image.png", true);  
req.send();  

function onUpdateProgress(e) {  
 if (e.lengthComputable) {  
 var percent_complete = e.loaded/e.total;  
 if (Math.round(percent_complete*200)>=20) {  
                    $("#progress").animate({  
                    width: Math.round(percent_complete*100)  
            }, 0);  
        }  
      }  
}  

function onTransferFailed(e) {  
    alert("Something went wrong. Please try again.");  
}  

function onTransferComplete(e) {  
   //Problem  
}  

My problem is I don´t know how to show the image which is now loaded. I hope anyone can help me :) Thanks ...

like image 320
tobi Avatar asked Sep 24 '10 19:09

tobi


1 Answers

You can do this using DATA URIs, but it's hard to make that work in all current browsers.

If caching options are set correctly, you can better load it twice: first using your AJAX request, then, after the image has been cached by the browser, another time using the usual image functions. The second time your image will not be retrieved from the server again, but the browser will use the cached file and show the image almost instantly.

like image 114
Marcel Korpel Avatar answered Nov 15 '22 00:11

Marcel Korpel