Adi.P
Adi.P

Reputation: 400

How to add a script tag dynamically using javascript and detect if the script failed to load the file?

I know how to add a script tag to the body or head using append functions. But if the file (example.js) that I am trying to add is not present, it gives an error. How do I detect if this happens?

Upvotes: 0

Views: 57

Answers (2)

charlietfl
charlietfl

Reputation: 171669

script elements have load and error events you can listen to.

Run whatever your dependent code is in a load event handler and do something else in error handler

Example loading jQuery :

var jQurl='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'

var s = document.createElement('script');
s.src = jQurl;
s.onerror = function(err) {
  console.log(err)
}
s.onload = init;

document.head.appendChild(s);

function init(){
  console.log('jquery version=', jQuery.fn.jquery)
  $('body').append('<h3>Loaded!</h3>');

}

Upvotes: 1

Juan de Dios H.
Juan de Dios H.

Reputation: 222

I think you could do something like the following:

  script = document.createElement('script');
  script.type = 'text/javascript';
  script.onerror = () => {
    // Whatever you want to do in case the load fails
  };
  script.src = '...' // your src for the script

  // After this, append the script to wherever you want in the HTML document

Hope it helps!

Upvotes: 0

Related Questions