[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 359
  • Last Modified:

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.
1 Solution
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.
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:-
ShanghaiDAuthor Commented:
Thank you! Exactly what I was looking for.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now