Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么像这样以编程方式导入JavaScript文件不会';不行?_Javascript - Fatal编程技术网

为什么像这样以编程方式导入JavaScript文件不会';不行?

为什么像这样以编程方式导入JavaScript文件不会';不行?,javascript,Javascript,我有一个直接导入HTML的函数 function include(filename){ var head = document.getElementsByTagName('head')[0]; script = document.createElement('script'); script.src = filename; script.type = 'text/Javascript'; head.appendChild(script); } 我想

我有一个直接导入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();
        });
    });
}
require(['Point.js', 'Grid.js'], function() {
    gridTest();
});
当然,使用现有脚本动态加载JavaScript会更舒适,您可能会执行以下操作:

function testRunner() {
    include('Point.js', function() {
        include('Grid.js', function() {
            gridTest();
        });
    });
}
require(['Point.js', 'Grid.js'], function() {
    gridTest();
});
看看RequireJS:

你必须试试这个

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

这是因为在加载脚本时已经加载了其他JSE。
您需要使用回调函数

在尝试使用文件之前,您需要确保文件已加载。尝试以下方法:

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

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

要获取js文件,我认为您需要将其作为对象来缓存和使用

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

这将从其
url
预取
js文件
,并添加到缓存中。您可以从那里访问库。

他将如何准确地同步确定这一点?;)你可以使用Modernizer,谢谢你的例子和答案!