且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用jQuery $ .getScript()方法包含多个js文件

更新时间:2023-12-04 22:11:58

答案是



c $ c> getScript()并等到所有脚本加载完毕,如下所示:

  $ .when(
$ .getScript(/mypath/myscript1.js),
$ .getScript(/mypath/myscript2.js),
$ .getScript(/ mypath / myscript3.js),
$ .Deferred(function(deferred){
$(deferred.resolve);
})
).done(function(){

//将代码放在这里,脚本全部加载

});

FIDDLE



另一个FIDDLE



在上面的代码中,添加Deferred并在 $ ()就像在jQuery调用中放置任何其他函数一样,如 $(func),它与

  $(function(){func();}); 

即它会等待DOM准备就绪,因此在上面的示例中 $。当等待所有要加载的脚本为DOM时准备好了,因为 $ .Deferred 调用可以在DOM准备好的回调中解析。




对于更通用的用途,一个方便的函数



接受任何脚本数组的函数函数可以像这样创建:

  $。getMultiScripts = function(arr,path){
var _arr = $ .map(arr,function(scr){
返回$ .getScript((path ||)+ scr);
});

_arr.push($。Deferred(function(deferred){
$(deferred.resolve);
}));

返回$ .when.apply($,_arr);
}

可以像这样使用

  var script_arr = [
'myscript1.js',
'myscript2.js',
'myscript3.js'
];
$ b $ .getMultiScripts(script_arr,'/ mypath /')。done(function(){
//加载所有脚本
});

其中路径将被添加到所有脚本中,并且也是可选的,这意味着如果数组包含完整的URL也可以做到这一点,并将所有路径放在一起

  $。getMultiScripts(script_arr).done(function (){... 






参数,错误等。



另外,请注意, done 回调将包含许多匹配传入脚本的参数,每个参数表示一个包含响应的数组

$ $ p $ $ getMultiScripts(script_arr).done(function(response1,response2,response3){ ...

其中每个数组将包含类似于 [content_of_file_loaded,status, xhr_object]
我们通常不需要访问这些参数,因为无论如何都会自动加载脚本,并且大多数时候 done 回调就是我们真的在知道所有脚本已被加载之后,我只是为了完整性而添加它,以及在需要访问加载文件的实际文本或需要访问每个XHR对象或类似内容的罕见情况下。

另外,如果任何脚本加载失败,失败处理程序将被调用,并且后续脚本将不会被加载。
  $。getMultiScripts(script_arr).done(function(){
// all done
})。fail(function(error){
//一个或多个脚本未能加载
})。always(function(){
//总是调用,成功和错误
});


I am trying to dynamically include javascript files into my js file. I did some research about it and find jQuery $.getScript() method would be a desired way to go.

// jQuery
$.getScript('/path/to/imported/script.js', function()
{
    // script is now loaded and executed.
    // put your dependent JS here.
    // what if the JS code is dependent on multiple JS files? 
});

But I am wondering whether this method can load multiple scripts at one time? Why I am asking this is because sometimes my javascript file is depending on more than one js files.

Thank you in advance.

The answer is

You can use promises with getScript() and wait until all the scripts are loaded, something like:

$.when(
    $.getScript( "/mypath/myscript1.js" ),
    $.getScript( "/mypath/myscript2.js" ),
    $.getScript( "/mypath/myscript3.js" ),
    $.Deferred(function( deferred ){
        $( deferred.resolve );
    })
).done(function(){

    //place your code here, the scripts are all loaded

});

FIDDLE

ANOTHER FIDDLE

In the above code, adding a Deferred and resolving it inside $() is like placing any other function inside a jQuery call, like $(func), it's the same as

$(function() { func(); });

i.e. it waits for the DOM to be ready, so in the above example $.when waits for all the scripts to be loaded and for the DOM to be ready because of the $.Deferred call which resolves in the DOM ready callback.


For more generic use, a handy function

A utility function that accepts any array of scripts could be created like this :

$.getMultiScripts = function(arr, path) {
    var _arr = $.map(arr, function(scr) {
        return $.getScript( (path||"") + scr );
    });

    _arr.push($.Deferred(function( deferred ){
        $( deferred.resolve );
    }));

    return $.when.apply($, _arr);
}

which can be used like this

var script_arr = [
    'myscript1.js', 
    'myscript2.js', 
    'myscript3.js'
];

$.getMultiScripts(script_arr, '/mypath/').done(function() {
    // all scripts loaded
});

where the path will be prepended to all scripts, and is also optional, meaning that if the array contain the full URL's one could also do this, and leave out the path all together

$.getMultiScripts(script_arr).done(function() { ...


Arguments, errors etc.

As an aside, note that the done callback will contain a number of arguments matching the passed in scripts, each argument representing an array containing the response

$.getMultiScripts(script_arr).done(function(response1, response2, response3) { ...

where each array will contain something like [content_of_file_loaded, status, xhr_object]. We generally don't need to access those arguments as the scripts will be loaded automatically anyway, and most of the time the done callback is all we're really after to know that all scripts have been loaded, I'm just adding it for completeness, and for the rare occasions when the actual text from the loaded file needs to be accessed, or when one needs access to each XHR object or something similar.

Also, if any of the scripts fail to load, the fail handler will be called, and subsequent scripts will not be loaded

$.getMultiScripts(script_arr).done(function() {
     // all done
}).fail(function(error) {
     // one or more scripts failed to load
}).always(function() {
     // always called, both on success and error
});