javascriptjqueryajaxpromisejavascript-namespaces

How to access a function or variable in a script run with $.getScript


Is there some way to access the namespace of a script after it is run with $.getScript? Since plugin is defined in the global scope, I would have thought I'd be able to run it.

index.js

$.getScript('plugin.js').then((...result) => console.log(result));

$.getScript('plugin.js').then(plugin());

plugin.js

function plugin()
{
  console.log("plugin.js");
  return "plugin";
}

_output__

ReferenceError: plugin is not defined
    at https://replit.org/data/web_hosting_uncache/abalter/loading-scripts-and-callbacks-1/index.js:5:25
[ 'var plugin = function()\n{\n  console.log("plugin.js");\n  return "plugin";\n}',
  'success',
  Promise {
    readyState: 4,
    getResponseHeader: [Function],
    getAllResponseHeaders: [Function],
    setRequestHeader: [Function],
    overrideMimeType: [Function],
    statusCode: [Function],
    abort: [Function],
    state: [Function],
    always: [Function],
    catch: [Function],
    pipe: [Function],
    then: [Function],
    promise: [Function],
    progress: [Function],
    done: [Function],
    fail: [Function],
    responseText: 'var plugin = function()\n{\n  console.log("plugin.js");\n  return "plugin";\n}',
    status: 200,
    statusText: 'success' } ]

https://repl.it/@abalter/loading-scripts-and-callbacks-1


Solution

  • The problem is with this line:

    $.getScript('plugin.js').then(plugin());
    

    then accepts a function as an argument, not a function call (unless said function call is a call to a higher-order function that returns a function to be put in the promise chain)

    You're calling plugin() at the same moment you're making the script request. You don't want that - you want to call plugin only after the request has finished. But at the time the getScript runs, plugin isn't defined in window scope yet. Inside of then, put a function that runs plugin once called:

    $.getScript('plugin.js').then(() => plugin());