【问题标题】:How can I know when Ajax calls are finished with getScript?我如何知道使用 getScript 完成 Ajax 调用的时间?
【发布时间】:2016-11-05 02:44:39
【问题描述】:

我正在使用 jQuery getScript 将 X 数量的 js 文件加载到我的页面中。这些 JS 页面中的每一个都有一个从数据库中获取数据的 AJAX 调用。

我在getScript 上使用.done 方法来查看所有文件何时已加载,但我需要等到所有AJAX 调用也已完成。

在做某事之前,如何通过getScript 等待 AJAX 调用在包含的文件中完成?

$.getMultiScripts(moduleIncludes, 'includes/js/modules/').done(function() {
    // All of the JS files have been included but we need to wait until those files have finished their AJAX call.     
});

// Get array of JS scripts to load
$.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);
}

【问题讨论】:

  • 让所有程序在某处写入完成状态。然后,您需要查询“某处”(服务器、本地存储或其他)以检查所有过程是否已完成。
  • @threadp 我将如何等待或检查这样的状态?
  • 安装一个setTimeout 处理程序来检查是否完成,如果一切都完成(加载),则执行进一步的代码。
  • @threadp 感谢您的建议。我会牢记这一点,但会继续寻找更稳定的解决方案。
  • 如果您知道可以使用计数器的文件数量。

标签: javascript jquery ajax


【解决方案1】:

您可以使用.ajaxStop()

每当一个 Ajax 请求完成时,jQuery 都会检查是否有 任何其他未完成的 Ajax 请求。如果没有剩余,jQuery 触发 ajaxStop 事件。

$(document).on("ajaxStop", function() {
  // do stuff when all `$.ajax()` call have complete
  $(document).off("ajaxStop")
});

$.getMultiScripts(moduleIncludes, 'includes/js/modules/').done(function() {
    // All of the JS files have been included but we need to wait until those files have finished their AJAX call.     
});

另一种方法是使用两次$.when.apply()。也就是说,将 ajax 调用推送到第二个数组中

"module1.js"

data.push($.get("/path/to/module1-resource"))

var modules = ["module1.js", "module2.js", "module3.js"];
// declare global `data` array
data = [];

$.getMultiScripts = function(arr, path) {

  var _arr = $.map(arr, function(scr) {
      return $.getScript(scr)
  });

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

$.getMultiScripts(arr)
.then(function() {
  console.log("getScript calls", arguments)
  $.when.apply($, data).then(function() {
    console.log("ajax calls", arguments)
  })
});

plnkr http://plnkr.co/edit/si2EsUZOciOwU4nAPlS9?p=preview

【讨论】:

  • 那真是太酷了——我想这会解决我的需求。
猜你喜欢
  • 2010-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多