Ok, I know this is 2017, 4 years later, but it seems the jQuery team never bothered about it, ok. I had the same problem and I think this is the solution, the actual intended way of using getScript in a local context. I noticed that there is no way that the code can be easily evaluated in a local context against your code that jQuery does not know how this happens. I did not go deeper, but if you look at the source of jQuery, then how it injects a script into a document, it is a genius, it generally avoids eval. Thus, the script worked as if it were imported using the script tag. Without further ado...
I decided to do the opposite, it better explains what is happening. Then you can undo it for this example.
If you notice that getScript actually sends a unique identifier to the server in the query string. I do not know why they did not mention this in the documentation. Use this to identify returned scripts. But you have to do something in the backend ...
let imports; $.getScript("scripts.php?file=abc.js", (data, textStatus, jqXHR) => { window[jqXHR.getResponseHeader('X-scriptID')](imports); alert (imports.name); });
abc.js:
imports.name = 'fred';
backend wraps the entire script, we get scripts.php:
// code that gets the file from file system into var $output $output = file_get_contents($_REQUEST['file']); // generate a unique script function name, sort of a namespace $scriptID = "__script" . $_REQUEST['_']; // wrap the script in a function a pass the imports variable // (remember it was defined in js before this request) we will attach // things we want to become local on to this object in script file $output = "window.".$scriptID."=function(imports) { ".$output." };"; // set the script id so we can find this script in js header ("X-scriptID: " . $scriptID); // return the output echo $output;
What happens since js requests the script via getScript, but it does not directly request the file that the PHP script uses to extract the contents of the file. I do this so that I can modify the returned data and attach the headers that are used for the identifier of the returned script (here is a great application in which there are so many requests).
When getScript runs the returned script in the browser, as usual, the actual contents of the script are not executed, just declaring a wrapper function with the unique name __script1237863498 or something like (the number was specified by getScript after requesting this script earlier) attached to the global window object. Then js uses this answer to start the wrapper function and inserts the properties into the import object ... that become local to query any scope.