Currently, I am working on implementing a require/load function that handles the retrieval and execution of remote JavaScript code. The function is functioning well, but I have been using a workaround to pass arguments by setting global variables. However, I am interested in learning the best practices for passing arguments in this scenario. Below is the snippet of the function responsible for loading the remote script:
Module.require = function (moduleName , args){
if (! Module.has(moduleName)){
dojo.xhrGet({
url: 'module.require.php',
handleAs: "javascript",
content : {
module : moduleName
},
load: function() {
},
error: function(errorMessage) {
console.log('there was an error with Module.require()');
console.error(errorMessage);
}
});
}
};
My main query pertains to the context in which moduleName
gets executed when the code from moduleName.js
is fetched and run dynamically. If it runs within the scope of the `Module.require` function, then referencing args
would be straightforward. However, if it operates in the global scope (window
), then local variable declaration techniques such as anonymous function calls (function(){}());
could be used. In the latter case, how can arguments be passed? I am hoping for a simple solution as I prefer not to send all arguments to the server, especially considering potential complexities involved in parsing them via PHP.
EDIT: A suggestion by James Khoury involved employing f.apply()
and f.call()
methods to pass arguments. Now, my concern revolves around understanding the execution context of the loaded script. If it happens within the function's scope, I assume invoking it like f.call(this , args);
should suffice. Additionally, is there a way to call an anonymous function? This query stems from my need to develop modules encapsulating user code while keeping their declared variables local, hence to maintain consistency, making sure the wrapper function remains non-global would be ideal.
Thank you.