Skip to main content
added 205 characters in body
Source Link
David
  • 3.9k
  • 2
  • 24
  • 17

I'm dynamically adding <script> tags to a page's <head>, and I'd like to be able to tell whether the loading failed in some way -- a 404, a script error in the loaded script, whatever.

In Firefox, this works:

var script_tag = document.createElement('script');
script_tag.setAttribute('type', 'text/javascript');
script_tag.setAttribute('src', 'http://fail.org/nonexistant.js');
script_tag.onerror = function() { alert("Loading failed!"); }
document.getElementsByTagName('head')[0].appendChild(script_tag);

However, this doesn't work in IE or Safari.

Does anyone know of a way to make this work in browsers other than Firefox?

(I don't think a solution that requires placing special code within the .js files is a good one. It's inelegant and inflexible.)

I'm dynamically adding <script> tags to a page's <head>, and I'd like to be able to tell whether the loading failed.

In Firefox, this works:

var script_tag = document.createElement('script');
script_tag.setAttribute('type', 'text/javascript');
script_tag.setAttribute('src', 'http://fail.org/nonexistant.js');
script_tag.onerror = function() { alert("Loading failed!"); }
document.getElementsByTagName('head')[0].appendChild(script_tag);

However, this doesn't work in IE or Safari.

Does anyone know of a way to make this work in browsers other than Firefox?

I'm dynamically adding <script> tags to a page's <head>, and I'd like to be able to tell whether the loading failed in some way -- a 404, a script error in the loaded script, whatever.

In Firefox, this works:

var script_tag = document.createElement('script');
script_tag.setAttribute('type', 'text/javascript');
script_tag.setAttribute('src', 'http://fail.org/nonexistant.js');
script_tag.onerror = function() { alert("Loading failed!"); }
document.getElementsByTagName('head')[0].appendChild(script_tag);

However, this doesn't work in IE or Safari.

Does anyone know of a way to make this work in browsers other than Firefox?

(I don't think a solution that requires placing special code within the .js files is a good one. It's inelegant and inflexible.)

Source Link
David
  • 3.9k
  • 2
  • 24
  • 17

How to tell if a <script> tag failed to load

I'm dynamically adding <script> tags to a page's <head>, and I'd like to be able to tell whether the loading failed.

In Firefox, this works:

var script_tag = document.createElement('script');
script_tag.setAttribute('type', 'text/javascript');
script_tag.setAttribute('src', 'http://fail.org/nonexistant.js');
script_tag.onerror = function() { alert("Loading failed!"); }
document.getElementsByTagName('head')[0].appendChild(script_tag);

However, this doesn't work in IE or Safari.

Does anyone know of a way to make this work in browsers other than Firefox?