Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6771841
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T15:28:49+00:00 2026-05-26T15:28:49+00:00

I need to use a javascript function from an external js file inside another

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T15:28:50+00:00Added an answer on May 26, 2026 at 3:28 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

A bunch of my JavaScript code is in an external file called helpers.js. Inside
I am trying to use some rails code withing a javascript and need to
I'm having problems trying to call a Javascript function from an enqueued javascript file
I need to run a javascript function from a phpunit test with selenium and
I am trying to pass 2 parameters to a javascript function.This code webview.loadUrl(javascript: function_to_call(););
I have a javascript which I didn't write but I need to use it
I have a large javascript which I didn't write but I need to use
I develop various web apps, use CSS and JavaScript extensively, and need to be
What's the minimum JavaScript I need if all I want to do is use
I need to use NSImage which appears need to be imported from <AppKit/AppKit.h> .

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.