我有这个直接在 HTML 中导入的函数

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

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

    head.appendChild(script);
}

我想用它来像这样以编程方式导入我的其他 JS
function testRunner(){
    include('Point.js');
    include('Grid.js');
    gridTest();
}

JS 显示在头部的 HTML 中,它们看起来不错......

但是其他 JS 看不到它。

为什么 ?

最佳答案

包含的脚本是异步加载的,因此 include() 函数在脚本文件完全加载之前返回。

您需要为脚本的 onload 事件传递一个回调:

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

然后像这样加载它:
function testRunner() {
    include('Point.js', function() {
        include('Grid.js', function() {
            gridTest();
        });
    });
}

当然,使用现有脚本动态加载 JavaScript 会更舒服,然后你可能会做这样的事情:
require(['Point.js', 'Grid.js'], function() {
    gridTest();
});

看看RequireJS:http://requirejs.org/

关于javascript - 为什么像这样以编程方式导入 JavaScript 文件不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8488486/

10-13 02:11
查看更多