1

我正在使用 jQuery 开发一个网页,我希望它仅在我的所有 JavaScript 文件完全加载后才执行一些代码。我的headHTML 部分有以下脚本。

<script src="supervisor/lib/jquery-1.6.min.js" type="text/javascript"></script>

在 jQuery 文件中,我插入了以下代码:

$.getScript('functions.js', function () {
  // code here
});

文件 functions.js 具有以下代码:

$.getScript('mask.js');
$.getScript('validations.js');
$.getScript('lotsofscripts.js');
// and more...

我希望这里的代码$.getScript()在加载所有其他 JS 后才执行,但这不会发生。实现这一目标的最佳方法是什么?

PS:我使用了很多,$.getScript()因为我发现将它们分开更容易,但我希望将它们插入同一个文件中。

4

4 回答 4

2

你总是可以只增加一个计数器。这样,您的 getScript 调用将保持异步,因为您不想做的就是更改它。坦率地说,您发现的任何并行加载脚本然后执行某些功能的打包解决方案可能只是一个更闪亮的版本:

var counter = 0;
var filesToLoad = ["mask.js", "validations.js", "lotsofscripts.js"];
var filesCount = filesToLoad.length;

// Increment counter each time a getScript completes
function incrementCounter() {
  if (++counter === filesCount) {
    // This code will execute after everything loads
  }
}

// Iterate through the files and run getScript on them,
// with incrementCounter as the callback
for (var i = 0; i < filesCount; i++) {
  $.getScript(filesToLoad[i], incrementCounter);
}

这是一个jsFiddle 示例

于 2011-06-03T20:26:55.783 回答
1

我建议HeadJS加载您的 JS 文件。您可以在完成特定文件或文件组后执行特定代码。看看,这是一个很棒的小项目。

于 2011-06-03T20:22:40.577 回答
1

假设您知道 js 脚本中定义的函数的名称,需要测试它是否已加载...

我使用 Underscore.js isFunction() 来解决这个问题(http://documentcloud.github.com/underscore/#isFunction

例如,如果 script.js 包含一个函数 myScriptFunction(),您可以编写一个函数来检查:

if (_.isFunction(myScriptFunction)) {
  // script.js is loaded
  // OK to move on to the next step
} else {
  // script.js is not loaded
  // check again later
}

我尝试绑定到事件以确定是否加载了 js 脚本文件,但它似乎不适用于所有浏览器。

于 2011-06-03T20:13:22.163 回答
-1

您可能想改用jQuery.ajax()。您可以将 async 选项设置为 false(使用 getScript 时默认为 true

于 2011-06-03T20:04:47.597 回答