Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Using the getScript() function on its own, I don't think you can. The problem is that the script is being loaded using AJAX (indeed, getScript is just a shorthand for a special $.ajax() function), and when the browser tries to execute the function on the next line, perhaps the server has not yet returned the file.

If you do not wish to use a callback function, you will need to use the jQuery $.ajax() function in its original form (and forget about the getScript()), and set the transfer as synchronous. This way, you can be sure that the script will be loaded before execution of your code continues:

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

$.getScript, and really all HTTP OP related jQuery functions are non-blocking calls by default. That is to say that the code doesn't hang while the operation completes. What this means is that your code above will most certainly fail because there is no way that $.getScript will load the script before the line attempting to execute the method runs. This is why callback functions are accepted as parameters.

However, what you're trying to do is possible. Once the script has been loaded you should be able to call it from anywhere. All that's necessary to avoid the method being called prior to the script being downloaded is setting the necessary flags.

var HelperFileLoaded = false; 
$.getScript('js/myHelperFile.js', function() { HelperFileLoaded = true; });

// ...

function btnSaveClick() {
    if(!HelperFileLoaded) return;
    myHelperFunction(); 
}

BenM's suggestion is possible but unless you're only making a single call to myHelperFunction it won't work as a solution because there will be no guarantee that the script will have downloaded before any other methods calling myHelperFunction have been triggered.

Your first one works fine if you're using JSONP, I do it that way often.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top