在 html5 浏览器中取消单个图像请求 [英] Cancel single image request in html5 browsers

查看:36
本文介绍了在 html5 浏览器中取消单个图像请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态加载(大)图像以绘制到 html5 画布中,如下所示:

I'm loading (large) images dynamically to draw into a html5 canvas, something like this:

var t = new Image();
t.onload = ...
t.src = 'http://myurl';

但每隔一段时间就会完全取消图片请求.

我想出的唯一方法是将 src 设置为 ''.即

The only way I came up with is setting src to ''. i.e.

t.src = ''

这适用于许多浏览器,但似乎只有 Firefox 实际上取消了对图像的 http 请求.

This works in many browsers, but it seems that only Firefox actually cancels the http request for the image.

我使用 Fiddler2 对此进行了测试,方法是禁用缓存并启用模拟调制解调器速度".然后运行 ​​a fiddle 来测试取消图像请求.(我很想听听其他关于如何测试这个的想法)

I tested this with Fiddler2 by disabling caching and enabling "emulate modem speed". Then running a fiddle to test canceling a image request. (I'd love to hear other ideas on how to test this)

我知道有一些方法可以取消所有请求(就像这个问题),但我只想取消一个.

I know there are ways to cancel all requests (as in this question), but I'd like to only cancel one.

对其他方法(尤其是在移动浏览器上)有什么想法吗?

Any ideas on other ways (especially on mobile browsers) to do this?

推荐答案

这是我设法让它在所有现代浏览器(Chrome、Safari、Mobile-Safari、Firefox 和 IE9)中工作的唯一方法.

This is the only way that I managed to get it to work in all modern browsers (Chrome, Safari, Mobile-Safari, Firefox, and IE9).

  • 加载一个空的隐藏的iframe
  • iframe
  • body 中附加一个 image 标签
  • img.onload 完成后,您可以使用该图像 dom 元素通过 drawImage()
  • 绘制到 html5 画布上
  • 如果要取消加载,请在 iframecontentWindow(或 execCommand("stop", false) 在 IE 中的 contentDocument 上).
  • 取消图片加载后,您可以重复使用 iframe 来加载更多图片.
  • Load an empty and hidden iframe
  • append an image tag to the body in the iframe
  • when the img.onload completes, you can use that image dom element to draw to an html5 canvas with drawImage()
  • if you want to cancel the load, issue a stop() on the iframe's contentWindow (or execCommand("stop", false) on contentDocument in IE).
  • after you cancel a image load, you can reuse the iframe to load more images.

我为此创建了一个类,并将 coffeescript 代码(它是编译的 javascript)放在 github 上:可取消的 Html5 图片加载器

I created a class for this, and put the coffeescript code (and it's compiled javascript) on github: Cancelable Html5 Image Loader

如果你想玩它,我还创建了一个 jsfiddle 来测试它.记得启动 Fiddler2(或类似的东西)以查看实际的网络请求是否真的被取消了.

If you want to play with it, I also created a jsfiddle to test it out. Remember to start Fiddler2 (or something like it) to see that the actual network request is really being canceled.

这篇关于在 html5 浏览器中取消单个图像请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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