Loading Javascript Dynamically and how to check if the script exists

Listening for events on script elements is not considered reliable (Source). One option that comes to mind is to use setTimeout() to poll for a variable that you expect to be defined in your external script. After x seconds, you could timeout your poll and consider the script as broken.

External Script: file.js:

var MyLibrary = { };

Main document:

var poll;
var timeout = 100; // 10 seconds timeout
var script = document.createElement('script');
script.type="text/javascript";
script.src="https://stackoverflow.com/questions/3768768/file.js";
document.body.appendChild(script);

poll = function () {
  setTimeout(function () {
    timeout--;
    if (typeof MyLibrary !== 'undefined') {
      // External file loaded
    }
    else if (timeout > 0) {
      poll();
    }
    else {
      // External library failed to load
    }
  }, 100);
};

poll();

Leave a Comment