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 ?
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/
That's because other JS-es are already loaded when you load your script. You need to use callback function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With