我怎么知道用getScript完成Ajax调用的时间?

编程入门 行业动态 更新时间:2024-10-26 22:20:25
本文介绍了我怎么知道用getScript完成Ajax调用的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am using jQuery getScript to load X amount of js files into my page. Each of those JS pages has an AJAX call in it that fetches data from the database.

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

I am using the .done method on getScript to see when all of the files have been loaded but I need to wait until all of the AJAX calls have been completed as well.

如何做才能通过getScript等待AJAX​​调用在包含的文件中完成?

How can I go about waiting for the AJAX calls to finish in the included files via getScript before doing something?

$.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); }

推荐答案

您可以使用 .ajaxStop()

You can use .ajaxStop()

每当Ajax请求完成时,jQuery都会检查是否存在 任何其他未完成的Ajax请求.如果不存在,则jQuery触发 ajaxStop事件.

Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.

$(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调用推入第二个数组

An alternative approach would be to use $.when.apply() twice. That is, push ajax calls into a second array

"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 plnkr.co/edit/si2EsUZOciOwU4nAPlS9?p=preview

更多推荐

我怎么知道用getScript完成Ajax调用的时间?

本文发布于:2023-08-02 13:27:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1278179.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我怎么   时间   getScript   Ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!