Dynamically Importing JavaScript

后端 未结 3 995
悲哀的现实
悲哀的现实 2021-01-13 16:52

What is the correct way to dynamically import JavaScript (.js) files into a parent JavaScript code, please?

I am using the following code, but it seems not correct:<

3条回答
  •  青春惊慌失措
    2021-01-13 17:28

    The reason you can't read the PETNAME variable is that dynamically injecting scripts like this is asynchronous and non-blocking. This means that your alert executes before the script has actually been loaded. Instead, you might have to poll for the existence of the PETNAME variable:

    var waitForPETNAME = function(){
            if (typeof PETNAME === 'undefined') {
                setTimeout(waitForPETNAME, 15);
            } else {
                // execute code that uses PETNAME
            }
        };
    
    waitForPETNAME();
    

    Also, a more fool-proof way to inject elements dynamically is to insert them before the first script element since you know for sure that a script element has to exist (otherwise you wouldn't be executing code). In other words, replace:

    document.getElementsByTagName("head")[0].appendChild(fileref)
    

    with:

    var insref = document.getElementsByTagName('script')[0];
    insref.parentNode.insertBefore(fileref, insref);
    

提交回复
热议问题