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.

Danny Fox
  • 38,659
  • 28
  • 68
  • 94
  • In case you are open to using jQuery you can use `.getScript` which has built-in error and success handling: http://api.jquery.com/jQuery.getScript/ – m90 Mar 25 '12 at 14:18
  • Maybe this will be helpful to you http://stackoverflow.com/questions/3248384/document-createelementscript-synchronously[link] – Philipp Braun Mar 25 '12 at 14:20

4 Answers4

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

Checksum
  • 3,220
  • 3
  • 23
  • 24
  • You will need to declare the onerror handler before you attach it to the document. Updated my answer to reflect the same – Checksum Mar 26 '12 at 02:10
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).

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

DEMO

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

//check if it didn't load
script.onerror = function() {
    alert('foo!');
}
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • Demo doesn't work when downloading nonexisten script from a valid address - e.g. script.src = 'https://apis.google.com/js/authNONEXISTENT.js' Only loaded is fired then. – Mi-La Mar 01 '16 at 21:10
-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.

Nik
  • 2,718
  • 23
  • 34