Can I use jquery getScript() without a callback?

froadie picture froadie · Nov 6, 2011 · Viewed 13.6k times · Source

I need to use a javascript function from an external js file inside another js file. This is basically the code I've tried:

$.getScript('js/myHelperFile.js');
myHelperFunction();

This doesn't work - I get an error of "myHelperFunction is not defined".

However, this code works:

$.getScript('js/myHelperFile.js', function(){myHelperFunction();});

I specifically want to be able to do it the first way - load the file at the top of my file, and then use any functions I need from there on. Is this possible, or am I misunderstanding how getScript works?

Answer

Useless Code picture Useless Code · Nov 6, 2011

Doing it "the first way" is not presently* possible with jQuery.getScript because it only supports asynchronous operations, and thus it returns immediately after being called.

Since it returns before your script has been downloaded when the script tries to invoke myHelperFunction(), myHelperFunction is undefined and causes that error.

*See the update at the bottom of this answer for a promising new method that will eventually allow you to write code that almost works like your desired style.

You could do it using jQuery.ajax with the async setting set to false with code that is something like this:

$.ajax({
  url: 'js/myHelperFile.js',
  async: false,
  dataType: "script",
});

myHelperFunction();

But as the documentation states:

synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

This is a very bad thing. If the server that is providing myHelperFile.js is slow to respond at any time (which will happen at some point) the page will become unresponsive until the request finishes or timesout.

It would be a much better idea to embrace the callback style which is used heavily throughout jQuery.

$.getScript('js/myHelperFile.js', function () {
   myHelperFunction();
});

You don't need to use an anonymous function either, you can put your code in a named function:

function doStuffWithHelper() {
   myHelperFunction();
}

$.getScript('js/myHelperFile.js', doStuffWithHelper);

If you need to load more than one dependency before calling myHelperFunction this won't work unless you set up some sort of system to figure out if all of your dependencies are downloaded before you execute your code. You could then set the callback handler on all of the .getScript calls to check that all of your dependencies are loaded before running your code.

var loadedScripts = {
    myHelperFile: false,
    anotherHelperFile: false
};

function doStuffWithHelper() {
    // check to see if all our scripts are loaded
    var prop;
    for (prop in loadedScripts) {
        if (loadedScripts.hasOwnProperty(prop)) {
            if (loadedScripts[prop] === false) {
                return; // not everything is loaded wait more
            }
        }
    }

    myHelperFunction();
}

$.getScript('js/myHelperFile.js', function () {
    loadedScripts.myHelperFile = true;
    doStuffWithHelper();
});
$.getScript('js/anotherHelperFile.js', function () {
    loadedScripts.anotherHelperFile = true;
    doStuffWithHelper();
});

As you can see, this kind of approach gets convoluted and unmaintainable fast.

If you do need to load multiple dependencies you would probably be better off using a scriptloader such as yepnope.js to do it.

yepnope( {
        load : [ 'js/myHelperFile.js', 'js/anotherHelperFile.js' ],
        complete: function () {
            var foo;
            foo = myHelperFunction();
            foo = anotherHelperFunction(foo);
            // do something with foo
        }
} );

Yepnope uses callbacks just like .getScript so you can not use the sequential style you wanted to stick with. This is a good tradeoff though because doing multiple synchronous jQuery.ajax calls in a row would just compound that methods problems.


Update 2013-12-08

The jQuery 1.5 release, provides another pure jQuery way of doing it. As of 1.5, all AJAX requests return a Deferred Object so you could do this:

$.getScript('js/myHelperFile.js').done(function () {
   myHelperFunction();
});

Being a asynchronous request, it of course requires a callback. Using Deferreds however has a huge advantage over the traditional callback system, using $.when() you could easily expand this to loading multiple prerequisite scripts without your own convoluted tracking system:

$.when($.getScript('js/myHelperFile.js'), $.getScript('js/anotherHelperFile.js')).done(function () {
  var foo;
  foo = myHelperFunction();
  foo = anotherHelperFunction(foo);
  // do something with foo
});

This would download both scripts simultaneously and only execute the callback after both of them were downloaded, much like the Yepnope example above.


Update 2014-03-30

I recently read an article that made me aware of a new JavaScript feature that may in the future enable the kind of procedural-looking-yet-async code that you wanted to use! Async Functions will use the await keyword to pause the execution of a async function until the asynchronous operation completes. The bad news is that it is currently slated for inclusion in ES7, two ECMAScript versions away.

await relies on the asynchronous function you are waiting on returning a Promise. I'm not sure how the browser implementations will behave, if they will require a true ES6 Promise object or if other implementations of promises like the one jQuery returns from AJAX calls will suffice. If a ES6 Promise is required, you will need to wrap jQuery.getScript with a function that returns a Promise:

"use strict";
var getScript = function (url) {
  return new Promise(function(resolve, reject) {
    jQuery.getScript(url).done(function (script) {
      resolve(script);
    });
  });
};

Then you can use it to download and await before proceeding:

(async function () {
  await getScript('js/myHelperFile.js');
  myHelperFunction();
}());

If you are really determined to write in this style today you can use asyc and await and then use Traceur to transpile your code into code that will run in current browsers. The added benefit of doing this is that you could also use many other useful new ES6 features too.