Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I handle a missing image in my plugin?

I have written a jQuery plugin called waitForImages. It basically gives the ability to run callbacks when images have loaded.

I recently received a feature request to somehow make the code notify when there is an error downloading an image.

Could the plugin call a function when an image is not found?

I thought about adding an extra argument that could be checked if the image was downloaded successfully or not.

image.onerror = function() {
     eachCallback.call(img.element, allImgsLoaded, allImgsLength, true);
}

Then the person could check the last argument to see if it is true, and if so, there was an error loading the image.

This idea smells to me though. What if I want to add an extra argument there later? Should the same callback be called for successful and failure of the image download?

I then thought about throwing an exception if the image is not found.

throw new Error(img.src ' + does not exist');

This however is not as flexible to catch, you'd need to call the plugin like so...

try {
   $('body').waitForImages();
} catch (exception) {
    // Which image didn't load?
    alert(exception.message);
}

What would be the best way to handle if an image didn't load in my plugin?

like image 303
alex Avatar asked Feb 25 '23 01:02

alex


1 Answers

I'd add a specific callback for error conditions.

You already have this:

$('selector').waitForImages({
    finished: function() {
        ...
    },
    each: function() {
       ...
    },
    waitForAll: true
});

You should consider changing it to:

$('selector').waitForImages({
    finished: function() {
        ...
    },
    finishedError: function() {
        ...
    },
    each: function() {
       ...
    },
    eachError: function() {
       ...
    },
    waitForAll: true
});

You could also use "finishedSuccess", if given, just to keep it consistent.

I prefer this for a few reasons:

  1. It separates out error handling
  2. You can have a different set of arguments for success or failure callbacks
  3. You easily add callbacks for different errors (unlikely for this case)

Please don't throw exceptions. An uncaught exception will break JavaScript execution. Probably not something you'll want to do just because an image didn't load.

like image 154
Brian McKenna Avatar answered Feb 26 '23 21:02

Brian McKenna