当我有一个脚本数组时,如何等待脚本加载

How do I wait till the scripts are loaded, when I have an array of scripts?

本文关键字:脚本 等待 何等待 加载 有一个 数组      更新时间:2024-04-10

我有一个脚本对象数组,如下所示:

_externalLibraries = [{name: 'knockout', url: '...'}, { name: 'knockoutValidation', url: '....'}];

然后我试着写下以下内容:

loadLibraries: function() {
  if (_externalLibraries.length === 0) {
    return;
  }
  _externalLibraries.forEach(function(lib){
    // Check if the libraries has been registered as "loaded."
    var librarysAlreadyLoaded = _loadedLibraries.filter(function(libAlreadyLoaded){
      return libAlreadyLoaded.name === lib.name;
    });
    // If it hasn't been loaded. Load it. This allows for mul;tiple widgets to be on the page.
    // Or this file (for what ever reason) to be called multiple times.
    console.log(librarysAlreadyLoaded);
    if (librarysAlreadyLoaded.length === 0) {
      $.getScript(lib.url, function(){
        _loadedLibraries.push({name: lib.name});
      });
    }
  });
},

基本上,我要做的是说,如果这个数组中的库还没有加载,就加载它。如果它还没有加载,那么就加载它,并将名称添加到"已加载库"的数组中。

问题是"ko是未定义的",至少在敲除和敲除验证中是这样。加载页面后,我可以在控制台中键入ko,然后查看它是否已加载。

我可以对代码进行哪些更改或添加,使其显示"好吧,我需要等待,直到这个数组中的每个脚本都加载完毕。"然后再做我想做的事情。

您可以使用$.when()Function.prototype.apply()

var _externalLibraries = [{
  name: "knockout",
  url: "https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"
}, {
  name: "knockoutValidation",
  url: "https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.js"
}];
var loadedLibraries = [];
$.when.apply($, $.map(_externalLibraries, function(lib) {
  return $.getScript(lib.url, function() {
    loadedLibraries.push(lib.name)
  })
}))
.then(function() {
  console.log(loadedLibraries, ko, ko.validation)
}, function err(jqxhr, textStatus, errorThrown) {
    console.log(textStatus, errorThrown)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>