2

I load external scripts to my site with this code:

 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = 'http://example.com/script.js';
 document.getElementsByTagName("head")[0].appendChild(script);

It works, but how to check, if it was an error at the loading? For example timeout, or a server error.

2

4 Answers 4

9

You can use the script.onerror to do something when there is an error loading it.

script.onerror = function() {
   alert("cannot load script");
}

document.getElementsByTagName("head")[0].appendChild(script);

Make sure you do it before you attach the script to the document

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

1 Comment

You will need to declare the onerror handler before you attach it to the document. Updated my answer to reflect the same
3

You can set onload (and possibly onerror - I've only used onload myself) on the script object before appending it to the document. The event will fire when the script loads successfully (or not, for onerror).

Comments

2

DEMO

//check if script was loaded
script.onload = function() {
    alert('loaded');
}

//check if it didn't load
script.onerror = function() {
    alert('foo!');
}

1 Comment

Demo doesn't work when downloading nonexisten script from a valid address - e.g. script.src = 'apis.google.com/js/authNONEXISTENT.js' Only loaded is fired then.
-1

If you own the script you're referring to, get it to call a function in the calling page to say its ready. Alternatively you could check for existence of some object that's declared in that script you're loading.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.