7

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 ...

1
  • +1 good question! I'm getting binary image and don't know how show the image Commented Sep 24, 2010 at 20:12

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

8 Comments

This seems to work. But it´s hard to see if the browser really loud the picture only one time. The Safari WebInspector for example shows it two times: electerious.com/share/Web%20Inspector.png
@tobias – Are your server settings correct? Can you show the headers with which the picture is sent?
I think so. Here´s the test site: electerious.com/share/loading.html
@tobias – Hey, I'm looking for laminate flooring; where did you get that? ;)
@tobias – There's another major flaw with your example: you should preload your image using an XMLHttpRequest and only after it's fully loaded you can assign the image to your img element. Now you're assigning the src in your HTML as well and the asynchronous XMLHttpRequest will download the image in parallel with the browser trying to render the image.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.