I am trying to dynamically add a script file that is an IIFE object
var DynamicLoadedFile = (function(){
const id=1;
const name='Object Name';
return {
init: function(){
console.log('Initialized');
},
getInfo: function(){
return {
id: this.id,
name: this.name
}
}
}
})(window.jQuery);
using jQuerys getScript method
$.getScript('script url').done(function(script){
// TODO: Do something with the script if we want
});
and I don't know how to get the name of the returned object (in this case DynamicLoadedFile) and then use that to run the 'init' or 'getInfo' functions.
i.e. - DynamicLoadedFile.init() or DynamicLoadedFile.getInfo();
I can get the name by using substring on the script that is returned
var objectName = script.substring(4,script.indexOf('=')).trim();
but once I have that I don't know how to use it to call the 'init' or the 'getInfo' methods.
i.e. - objectName.init() or objectName.getInfo();
Does anyone have any ideas? Or suggestions?
Thanks, Tim
varand executed (bygetScript) at global scope, the variable is a property of thewindowobject, sowindow[objectName].init();will do it. See some of the answers to the linked question for details.setTimeout(function() { /*...*/ }, 0);wrapper should deal with that.windowwhen they're loaded, with the reference to the object as a property on that event. Your main script listens for the custom event and uses the object when it arrives.)