0

Edit: bolded the reason this isn't a duplicate. It was already three words from the start, it was already repeated for emphasis.

Given an HTMLImageElement that's already loaded (load or error event already fired), does anybody know of a good way to tell if the load failed?

Strategies I've come up with:

  • img.src = img.src then catch the load or error event. Browsers seem to optimize this away and not actually make a network request, but I'd be much more comfortable with a solution that doesn't assume optimizations.
  • Change the alt text then see if the size changed. Very tough to make this robustly interoperate with the page's CSS and external event listeners on the image.

Edit: bolded the reason this isn't a duplicate, because apparently putting it in the first sentence and wording it two different ways still didn't get anybody to pay attention.

twhb
  • 4,294
  • 2
  • 20
  • 23
  • How about just `img.src = img.src + '?tada'` to make the image reload and fire the events. – adeneo Sep 30 '16 at 21:46
  • Possible duplicate of [Browser-independent way to detect when image has been loaded](http://stackoverflow.com/questions/821516/browser-independent-way-to-detect-when-image-has-been-loaded) – CMedina Sep 30 '16 at 21:51
  • @adeneo maybe I was unclear. `img.src = img.src` does work, I'm just looking for something better. – twhb Sep 30 '16 at 21:51
  • @CMedina not a duplicate, that question regards images that haven't yet loaded. – twhb Sep 30 '16 at 21:53
  • "I'd be much more comfortable with a solution that doesn't assume optimizations". So no relying on cache? – Joseph Marikle Sep 30 '16 at 22:00
  • Oh, okay, I assumed `img.src = img.src` didn't work in all browsers, but that's probably just older IE, which doesn't fire the events when the image is already cached, and requires the `img.complete .. img.onload()` hack. – adeneo Sep 30 '16 at 22:03
  • @JosephMarikle yes, it's rather ridiculous overhead when the task is just reading a boolean that's stored internally but apparently inaccessible. Also, Chrome doesn't even hit the cache here, just fires events, which would be fine but I don't think it's specified or reliable behavior. – twhb Sep 30 '16 at 22:07
  • @twhb I had an answer that I deleted, but it stated "Just treat it like a preloader. If the image has already been loaded, the browser will just load from cache, so very little overhead." I had this code: https://jsfiddle.net/jtgb0fvv/. Every modern browser should fire the events for the newly created image object. Is that something that fits your needs? – Joseph Marikle Sep 30 '16 at 22:12
  • @JosephMarikle thanks, but no, as I stated under `img.src = img.src` I'm requesting something without high overhead or relying on unspecified behavior. – twhb Sep 30 '16 at 22:18

0 Answers0