XMLHttpRequest JS Image loading

不想你离开。 提交于 2019-12-07 00:16:07

问题


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:


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.



来源:https://stackoverflow.com/questions/3790471/xmlhttprequest-js-image-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!