0

A common example of loading an image in JS to draw onto an HTML5 canvas is:

var canvas = $("#mycanvas")[0];
var context = canvas.getContext("2d");
var img = new Image();
img.src = 'URL HERE';
img.onload = function() {
    context.drawImage(img, 0, 0);
};

BUT how do we handle the case where the image failed to load?

e.g. when loading JSON data with JQuery there's a .fail method for handling load failures:

$.getJSON(url)
    .done(function(data, statusText, jqXHR) {
        // data loaded ok
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
        // error loading data - ERROR HANDLING HERE
    })
;

Great, but is there some equivalent in JS for handling image loading errors? Is there some other event similar to .onload but which triggers on failure to load? Or does .onload trigger in either case?

Similar problem when loading a video into a video tag:

var videoElement = $("#myvideo")[0];
$("#mvideo").append("<source src='URL HERE' type='TYPE STRING HERE'>");
videoElement.load();
videoElement.play();

i.e. how to we detect a load failure so we can add error handling code?

J_B
  • 31
  • 5
  • or since this is jQuery this may be better suited: http://stackoverflow.com/questions/1977871/check-if-an-image-is-loaded-no-errors-in-javascript –  Oct 22 '14 at 19:54

1 Answers1

1

Yes, use the onerror property:

img.onerror = function() {
    this.src = "DEFAULT SOURCE FOR ERROR LOADED IMAGES";
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Thanks! Will try that shortly. Does that event apply to video elements too, or is there a different one (ref latter part of question)? Cheers – J_B Oct 23 '14 at 09:31