jQuery Best Practice: Can I/Should I test for file not found error 404?

I'm programatically appending table rows with the following code:

$.getJSON('cfc/schoollibraries.cfc?method=getLibraryList&returnformat=JSON', function(json) {
 var myHTML = '';
  $.each(json.DATA, function(i,col) {
   myHTML += '<tr><td>' + col[0] + '</td><td>' + col[1] + '</td><td><img src="/images/sponsoredlibraries/' + col[2] + '" width="80"></td><td>' + col[3] + '</td></tr>';
  $('#tsTable tbody').append(myHTML);

Many of the referenced image files have not yet been uploaded, so I get many 404 errors when the script tries to load "missing" image files.

Is it possible in the $.each loop to first test if the file exists and then only execute the '<img src="/images/sponsoredlibraries/' + col[2] + '" width="80">' part of the code if it does in fact exist so that I then avoid getting the 404 errors?

If it can be done, should it be done (is it best practice) or does it not really matter?  (Would the additional time in testing for each file's existence in the looping offset the time of getting the failed 404 error messages)?

Hope this makes sense.
Who is Participating?
BuggyCoderConnect With a Mentor Commented:
you can make an ajax call for each image you get and process only if the call is successfull like this:-
$.each(json.DATA, function(i,col) {
   var imagePath = "/images/sponsoredlibraries/' + col[2];
    error: function()
        //file not exists
    success: function()
           myHTML += '<tr><td>' + col[0] + '</td><td>' + col[1] + '</td><td><img src="/images/sponsoredlibraries/' + col[2] + '" width="80"></td><td>' + col[3] + '</td></tr>';
  $('#tsTable tbody').append(myHTML);

Open in new window

Refer here for more details:-
best practice would be not to reference images that don't exist in the first place. i.e. "getLibraryList" should return a clean list of images that excludes images that don't exist yet.

if that is simply not possible then i would suggest the overhead of making the http request to the server just to check if the image exists would negate the benefits and you may as well just get the 404s.
ShanghaiDAuthor Commented:
Thank you! Exactly what I was looking for.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.