3

I have pieced together a jQuery snippet using an AJAX call to call an external file, which works just great as shown:

jQuery.ajax({
   type: "GET",
   url: "http://www.domain.com/external.js",
   dataType: "script"
});

I only need (to create) the external file under certain conditions, but if it is not present, I get a 404 error in the browser console. I want it to do absolutely nothing (ignore) if the file is not present.

The closest related post I found is How to include external html if exists, else do nothing? but it doesn't do nothing, it runs another function:

jQuery(function() {
jQuery.ajax({
    type: "GET",
    url: "http://www.domain.com/external.js",
    cache: false,
    dataType: "script"
    success: function(html){
        $('#test').html(html);
    }
  });
});

QUESTION: How would I go about ignoring any warnings if the file is NOT present, but run the file if it is?

Could I just do this?

jQuery(function() {
jQuery.ajax({
    type: "GET",
    url: "http://www.domain.com/external.js",
    cache: false,
    dataType: "script"
    success: ;
    }
  });
});

EDIT RESPONSE TO LANCE:

Because I didn't know about it! Wow, is it really that easy? Like this?

try { 
  jQuery.ajax({
    type: "GET",
    url: "http://www.domain.com/external.js",
    dataType: "script"
  });
}
catch(e){
  /* MOVE ALONG */      
}
Community
  • 1
  • 1
KillerDesigner
  • 485
  • 1
  • 6
  • 18

1 Answers1

2

How about just using try/catch?

try{
    /* stuff I want to do */
}catch(e){
    /* Don't display any error.  Just move along.  Nothing to see here.
}
Lance
  • 3,824
  • 4
  • 21
  • 29