Search code examples
jquerygetscript

jQuery getScript not working, or I'm using it wrong


I'm having trouble getting jquery's $.getScript to work. Here's a test file, demo.html:

<!DOCTYPE html>

<script src="/xyz/scripts/jquery-1.11.0.min.js"></script>
<script>
    function wow() { return 3; }
</script>

<h1>Demo</h1>

<script>
    console.log(wow);
    console.log(wow());
</script>

When I browse to this in Chrome on Windows 10, the following is displayed in the console:

Navigated to https://example.org/xyz/tools/demo.html
demo.html:11 ƒ wow() { return 3; }
demo.html:12 3

which is correct.

Then I move the function definition to a file called myModule.js:

function wow() { return 3; }

and create demo2.html, which is demo.html with the function definition replaced by a getScript call:

<!DOCTYPE html>

<script src="/xyz/scripts/jquery-1.11.0.min.js"></script>
<script>
    $.getScript("myModule.js");
</script>

<h1>Demo</h1>

<script>
    console.log(wow);
    console.log(wow());
</script>

This time I get

Navigated to https://example.org/xyz/tools/demo2.html
demo2.html:11 Uncaught ReferenceError: wow is not defined
at demo2.html:11

Am I misunderstanding what $.getScript is for or how it's used?

Addendum

In response to the suggestion to wrap my console.log calls in a $.ready wrapper, I tried the following:

<!DOCTYPE html>

<script src="/xyz/scripts/jquery-1.11.0.min.js"></script>
<script>
    $.getScript("myModule.js");
</script>

<h1>Demo</h1>

<script>
$.ready(function() {
    console.log(wow);
    console.log(wow());
});
</script>

This time I got no error message but, also, the values of wow and wow() weren't written to the console.


Solution

  • $.getscript

    https://api.jquery.com/jquery.getscript/

    This is a shorthand Ajax function, which is equivalent to:

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

    so $.getscript makes an asynchronous call, so your code is the equivalent of:

    • $.getscript - start loading the script
    • console.log(wow) - can't find it yet as script not yet loaded
    • ... finish loading script

    You can use the callback to execute code when the script has loaded:

    $.getScript("myModule.js", function() {
        console.log(wow);
        console.log(wow());
    });