简体   繁体   中英

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

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.

You must try this.

window.onload = function(){ 
var s = document.createElement('script'); 
s.src = 'YourScript.js'; 
document.getElementsByTagName('body')[0].appendChild(s); 
}

You need to be sure that the files have loaded before you try to use them. Try something like:

function include(filename){
    ...
    return true;
}

if (include("grid.js")){
    testgrid();
}

To bring js files, i think you need to fetch it as objects to cache and use.

function preFetchResources(url) {
                var o = document.createElement('object');
                o.data = url;
                o.width = 0;
                o.height = 0;
                document.body.appendChild(o);
            }

This will prefetch a js file from its url and add in cache. You can access the library from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM