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:
And then load it like this:
Of course using an existing script for dynamic loading of JavaScript would be much more comfortable, you could then probably do something like this:
Have a look at RequireJS: http://requirejs.org/