Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

javascript - Cancel single image request in html5 browsers

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';

But every once in a while would like to cancel the image request completely.

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

t.src = ''

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...