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?
Doing it “the first way” is not presently* possible with
jQuery.getScriptbecause 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(),myHelperFunctionisundefinedand 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.ajaxwith theasyncsetting set tofalsewith code that is something like this:But as the documentation states:
This is a very bad thing. If the server that is providing
myHelperFile.jsis 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.
You don’t need to use an anonymous function either, you can put your code in a named function:
If you need to load more than one dependency before calling
myHelperFunctionthis 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.getScriptcalls to check that all of your dependencies are loaded before running your code.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 uses callbacks just like
.getScriptso you can not use the sequential style you wanted to stick with. This is a good tradeoff though because doing multiple synchronousjQuery.ajaxcalls 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:
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:
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
awaitkeyword to pause the execution of aasyncfunction until the asynchronous operation completes. The bad news is that it is currently slated for inclusion in ES7, two ECMAScript versions away.awaitrelies 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 wrapjQuery.getScriptwith a function that returns a Promise:Then you can use it to download and
awaitbefore proceeding:If you are really determined to write in this style today you can use
asycandawaitand 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.