0

I'm trying to load an external JavaScript file via jQuery's .ajax() function (tried .getScript(), but it has the same problem).

According to the documentation, and testing, it doesn't fire error events, or even any of the global AJAX events when there is an error when loading script's from a remote source.

As far as I can see, the only event that is fired in the success event.

My question is: how can I detect if the remote script fails to load.

I can't alter the remote script, but I can detect if it has loaded. (By checking if a variable is defined).

4
  • Is it possible to just link to the external JavaScript file using <script> tags? Or copy it locally so you know it will be available? Commented Dec 20, 2011 at 18:11
  • when you say external javascript, do you mean a script from the same domain or a different one? if it's from a different one than the same origin policy won't allow you to load it via ajax Commented Dec 20, 2011 at 18:15
  • @mblase75 I load scripts during the script execution, so can't use <script> tags. Commented Dec 20, 2011 at 18:29
  • @stratton Loading from another domain. jQuery does it by adding a script tag. Commented Dec 20, 2011 at 18:30

2 Answers 2

1

Set a Timeout for a period of time, and in the success callback cancel the timeout. If the timeout fires then you can cancel the request and try again and / or perform your error handling.

Sign up to request clarification or add additional context in comments.

Comments

1

jQuery "helpfully" evaluates scripts for you. If you want to avoid this, you can set manually set the dataType:

$.ajax({
           url : '/foo'
    , dataType : 'text'
    ,  success : function(){ ... }
});

which will prevent jQuery from evaluating the script. You can then eval it yourself, wrapped in a try/catch.

1 Comment

that wasn't mentioned when I posted this :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.