Dynamically Importing JavasScript

試著忘記壹切 提交于 2019-12-01 06:54:43

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);

You can't use variables and functions defined in the external JS file immediatly after inserting the <script> tag. It takes the browser a few milliseconds to load the file and execute it.

You would have to work with some kind of callback in order to have the proper loading order for your JavaScript.

For proper conditional loading of JavaScript have a look at Require.js. There the Asynchronous Module Definition pattern is implemented.

In svk.js add the following (after the variable deceleration):

svkLoaded();

In the master code file add the following:

function svkLoaded()
{
    alert("Pet Name: " + PETNAME);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!