Sometimes in a web app, you'll want to load a script externally. The only problem is if you need to reference something within the external library, which you should only do once it's definitely loaded.

Here's a tip that works with all browsers to ensure the script is loaded before running your dependant code.

NewCommand line for non-techies

I've published 37 videos for new developers, designers, UX, UI, product owners and anyone who needs to conquer the command line today.

Here's the JavaScript code to load the external library with a callback passed in:

function loadExtScript(src, callback) {
  var s = document.createElement('script');
  s.src = src;

  // if the callback
Firefox allows you to listen for the onload event on the script element:
s.onload = callback;
With Internet Explorer you can wait for a state change on the script element:
s.onreadystatechange = function() {
  if ( this.readyState != "loaded" ) return;;
The problem comes with Safari - there's no event change for Safari, so we can't tell when the script has loaded. This is the solution I came up with (and this solution should also work with Opera):
function loadExtScript(src, test, callback) {
  var s = document.createElement('script');
  s.src = src;

  var callbackTimer = setInterval(function() {
    var call = false;
    try {
      call =;
    } catch (e) {}

    if (call) {
  }, 100);
The function takes a test as a parameter. Since you are the designer of the app, you'll know what successful test is. Once this test is true, it will execute the callback. A simple test could be to check whether a function exists, for example:
loadExtScript('/fixpng.js', function() {
  return (typeof fixpng == 'function');
}, myCallbackFunction);

Want more?

Posts, web development learnings & insights, exclusive workshop and training discounts and more, direct to your inbox.

I won't send you any spam, and you can unsubscribe at any time. Powered by ConvertKit