0

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

4
  • 1
    Manual for getScript says, “The callback is fired once the script has been loaded but not necessarily executed.” - so you can probably not rely on the object already existing at that point. Commented Sep 11, 2020 at 6:18
  • Since it's created with var and executed (by getScript) at global scope, the variable is a property of the window object, so window[objectName].init(); will do it. See some of the answers to the linked question for details. Commented Sep 11, 2020 at 6:19
  • @CBroe - Wow. I did not know that. The few times I used it (years ago), it had always been executed. Rushman, a setTimeout(function() { /*...*/ }, 0); wrapper should deal with that. Commented Sep 11, 2020 at 6:21
  • (I would encourage you to find an alternative to doing this, but that's not what you asked. :-) But for what it's worth, you could make the scripts that you're loading this way not create globals, but instead fire a custom event on window when 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.) Commented Sep 11, 2020 at 6:23

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.