XMLHttpRequest JS Image加载 [英] XMLHttpRequest JS Image loading

查看:214
本文介绍了XMLHttpRequest JS Image加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个通过XMLHttpRequest()加载图像的网站。 (XMLHttpRequest因为我想代表用户一个%进度条)

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

我的代码:

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

推荐答案

你可以使用DATA URI来做到这一点,但是很难做到在所有当前浏览器中都可以使用。

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

如果正确设置了缓存选项,您可以更好地加载它两次:首先使用您的AJAX请求,然后,在缓存图像之后通过浏览器,另一次使用通常的图像功能。第二次不再从服务器检索图像,但浏览器将使用缓存的文件并几乎立即显示图像。

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.

这篇关于XMLHttpRequest JS Image加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆