Dynamically Importing JavaScript

2.1k views Asked by At

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:

    function loadjscssfile(filename, filetype)
{
    //if filename is a external JavaScript file
    if (filetype=="js")
    {
        var fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
    }
    //if filename is an external CSS file
    else if (filetype=="css")
    {
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    if (typeof fileref!="undefined")
    document.getElementsByTagName("head")[0].appendChild(fileref)
}

I think, the code is not correct, because, in the master JavaScript code, I can no read variables defined in the imported code, such as:

var fileRef = loadjscssfile('Language/svk.js', 'js');
alert("Pet Name: " + PETNAME);

imported svk.js file contains the only code:

// JavaScript Document
var PETNAME = "Beauty";

Thank you.

3

There are 3 answers

3
mVChr On BEST ANSWER

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);
1
Sirko On

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.

1
Yaniro On

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