Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why importing JavaScript files programatically like this doesn't work?

Tags:

javascript

I have this function which is imported directly in the HTML

function include(filename){
    var head = document.getElementsByTagName('head')[0];

    script = document.createElement('script');
    script.src = filename;
    script.type = 'text/Javascript';

    head.appendChild(script);
} 

And I want to use it to import my other JSs programatically like this

function testRunner(){
    include('Point.js');
    include('Grid.js'); 
    gridTest();
}

the JSs are showing in the HTML in the head and they look ok...

But the other JSs cannot see it.

Why ?

like image 707
Cristiano Fontes Avatar asked Jun 17 '26 01:06

Cristiano Fontes


2 Answers

The included scripts are loaded asynchronously, so the include() function returns before the script file has been fully loaded.

You need to pass a callback for the onload event of the script:

function include(filename, cb){
    var head = document.getElementsByTagName('head')[0];

    script = document.createElement('script');
    script.src = filename;
    script.type = 'text/Javascript';
    script.onload = cb;

    head.appendChild(script);
} 

And then load it like this:

function testRunner() {
    include('Point.js', function() {
        include('Grid.js', function() {
            gridTest();
        });
    });
}

Of course using an existing script for dynamic loading of JavaScript would be much more comfortable, you could then probably do something like this:

require(['Point.js', 'Grid.js'], function() {
    gridTest();
});

Have a look at RequireJS: http://requirejs.org/

like image 175
ThiefMaster Avatar answered Jun 19 '26 14:06

ThiefMaster


That's because other JS-es are already loaded when you load your script. You need to use callback function.

like image 32
Nick Shvelidze Avatar answered Jun 19 '26 14:06

Nick Shvelidze